/*-------------------------------------------------------------------------

***************** Modification History ***********************************
   @doc
   @module Menufunc.c - Menu functionality |
   @end

	Revision History
 	Date						Author								Purpose			
 	06-Sep-2005		CHIA Lee Chyi				ECR Integration

$Log: /SoftPay/SPK2SIM/Source/Ui/menufunc.c $

**************************************************************************

   Copyright (C) 1999 by VeriFone, Inc.

   All rights reserved.  No part of this software may be reproduced,
   transmitted, transcribed, stored in a retrieval system, or translated
   into any language or computer language, in any form or by any means,
   electronic, mechanical, magnetic, optical, chemical, manual or otherwise,
   without the prior written permission of VeriFone, Inc.

---------------------------------------------------------------------------*/

/****** TEST FIX *******/
#ifdef IMAM_LOG
#ifndef LOGSYS_FLAG
#define LOGSYS_FLAG
#endif
#endif

#define VSMENUS_C
#include <project.h>
//#include <beetle.h>
//#include <beetleplug.h>

#include <aclconio.h>
#include <applidl.h>
#include <aclutil.h>
#include <aclstr.h>
#include <stdlib.h>
#include <string.h>
#include <acldev.h>
#include <VarRec.h>


#ifdef ICC_DEFINED
#include <libvoy.h>
#endif

/** /#define DEBUG_VSMENUS*/
#ifdef DEBUG_VSMENUS
#define DEBUG_95
#endif

#include <define.h>
#include <transact.h>
#include <menufunc.h>
#include <menus.h>
#include <gds.h>
#include <tct.h>
#include <lct.h>
//#include <lct1.h>
#include <pct.h>
#include <cct.h>
#include <tblutil.h>
#include <confio.h>
#include <mem.h>
#include <util.h>
#include <date.h>
#include <list.h>
#include <comm.h>
#include <msg.h>
#include <msgfuncs.h>
#include <ui.h>
#include <logo.h>
#include <passwd.h>
#include <appl.h>
#include <operate.h>
#include <oper.h>
#include <init.h>
#include <card.h>
#include <tran.h>
#include <spdebug.h>
#include <sizes.h>
#include <scalls.h>
#include <print.h>
#include <pinpad.h>
#include <ppicge.h>
#include <clerk.h>
#include <pcheck.h>
#include <file.h>
#include <mdlfuncs.h>
#include <codesec.h>
#include <mbtx3.h>
#include <funcids.h>
#include <table.h>
#include <form.h>
#include <msngr.h>
#include <modem.h>
#include <vidnld.h>
#include <mbtx2.h>

#ifdef FHANDLE
#undef FHANDLE
#endif

#include <eeslapi.h>
#include <logsys.h>
#include <mamevent.h>
#include <vmac.h>
//#include <tma.h>
#include <messenger.h>
#include <tmadef.h>
#include <cardslot.h>

#include <everest.h>
#include <svc.h>

#include "..\..\hostsrc\imamsrc\imamsrc.h"
#include "..\..\hostsrc\imamsrc\imammenu.h"

//meca 20041023 -- from cashcard O3750 -- start
#ifdef CASHCARD_DEFINED
#include "..\..\hostsrc\AS2805\AS28SAM.h"
#include "..\..\hostsrc\AS2805\AS28IPP7.h"
#include "..\..\hostsrc\cashsrc\cashppad.h"
#include "..\..\hostsrc\cashsrc\cashipp.h"
#endif //CASHCARD_DEFINED
//meca 20041023 -- from cashcard O3750 -- end



extern long lnTranTitleMessage;

//meca 20041023 -- fixed from cashcard O3750
static VS_BOOL F2_F4_Flag;	//alvin_m1
#ifdef CASHCARD_DEFINED
extern VS_BOOL fGblAcqKEKLoaded;
extern VS_BOOL fGblMutualAuthSuccess;
#endif //CASHCARD_DEFINED
//meca 20041023 -- fixed from cashcard O3750

static long lnAllocateMenu(void);
static int inFirstLn(void);
static int inFirstScreen(MenuItem*);
static int inGetLastMenu(int,int*,int,int);
static int inGetTransMsgID(int inOperationCode,int inSubOperationCode,long* plnTranMsg);

void vdPrintDebugLog(void);

Menu* pmeCurrentMenu = NULL_CH;
MenuElement* MenuList = NULL_CH;
MenuItem* pmeScrollItem = NULL_CH;

//static int inCurrentMenuIndex = ROOT_MENU_INDEX;
int inCurrentMenuIndex = ROOT_MENU_INDEX;  //, so that can be refered in imammenu.c file
static int inCurrentScrollItem = 0;
static int inDisplayLeftToRight = TRUE;
static int inFirstScrollItem = 0;
static int inFirstMenuKey = KEY_CR;
static int inLastMenuKey = KEY_CR;
static int inLoadingMoreFailed = TRUE;
static int inNumberOfItemsAtEnd = 0;
static int inNumScrollingMenuItems = 0;
static long lnCurrentMenuTitle = 0L;

int inScrollLeftKey = KEY_STR;
int inScrollRightKey = KEY_PND;

#define     ITEMS_PER_PAGE          4
#define     ITEMS_PER_FIRST_PAGE    3

#define     NUM_ITEMS_PER_PAGE  (inCurrentScrollItem == 0 ? ITEMS_PER_FIRST_PAGE : ITEMS_PER_PAGE)

/* MAM Externals */
extern int inMAMAvailable;
extern int hConsoleS;

/* MAM Event globals */
/*********************/
unsigned char pucMAMEventData[450];
unsigned short usMAMEventDataSize;
char pchSenderLogicalName[20];
int inVMACCardSelect = 0;

//ATS Bug Fix 35
long lnAppActivateEvent = 0L;
#ifdef TMA_DEFINED
/* TMA Variable record buffer */
extern unsigned char pucTMAFlexi;
#endif

extern unsigned long lnImamMenuItem;
extern unsigned long lnBackLightTimer;
extern int inImamUnlockKeyboard;
extern int inImamTerminalModel;
extern int inImamLineNumber;

Menu* pmeGetCurrentMenu(void) {
    return (pmeCurrentMenu);
}

short shGetCurrentMenuID(void) {
    return (inCurrentMenuIndex);
}

int inGetIndexForMenu(int inMenuNum) {
    int inMenuIndex,
    inNumMenus,
    inSearchIndex;

    /** /pdebug(("--inGetIndexForMenu(%d)--", inMenuNum));*/
    inMenuIndex = -1;
    inSearchIndex = 1;
    for (inNumMenus = MenuList[0].meMenu.mNumMenuItems; inNumMenus; --inNumMenus) {
        if (MenuList[inSearchIndex].meMenu.mMenuIdentifier == inMenuNum) {
            inMenuIndex = inSearchIndex;
            break;
        }
        inSearchIndex += MenuList[inSearchIndex].meMenu.mNumMenuItems + 1;
    }
    return    (inMenuIndex);
}

/*-------------------------------------------------------------------------
    Function :  inFirstLn
    Description : Returns the first line to display the screen addressable
                  menus for the different platforms - 39x, 4xx, 3200
    Parameters :

    Returns :    VS_SUCCESS, VS_ERR
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   07/31/96 Donncha_h1          Creation
--------------------------------------------------------------------------*/
static int inFirstLn(void) {
    /** /pdebug(("--inFirstLn--"));*/

    switch (obDisp.inTerminalType) {
    case TERMINAL_OMNI_3200:
        return(1); /* These run vertically on Omni 3200 */
    default:
        return(1);
    }
}


/*-------------------------------------------------------------------------
    Function :  inGetMenusFileName
    Description : Called at power-up to get the correct menusXXX.dat file
                  for the platform, i.e. 392, 395 and 470.
    Parameters : pchMenusFileName = name of appropriate .dat file name
                 inSizeOf         = size of first parameter
    Returns :    VS_SUCCESS, VS_ERR
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   07/25/96 Donncha_h1          Creation
      1   09/19/96 Donncha_H1 Added 396 term type
--------------------------------------------------------------------------*/
int inDefaultGetMenusFileName(char* pchMenusFileName,int  inSizeOf) {
    /** /pdebug(("--inGetMenusFileName--"));*/
    memset(pchMenusFileName, 0, inSizeOf);
    switch (obDisp.inTerminalType) {
    case TERMINAL_OMNI_3200:
        if (srGDS.fHandHeld)
            strcpy(pchMenusFileName, "menuhh.dat");
        else
            strcpy(pchMenusFileName, "menuct.dat");

        break;

    default:
        return(VS_ERR);
    }

    return (VS_SUCCESS);
}

/*-------------------------------------------------------------------------
    Function :  inGetFieldWidth
    Description : returns the field width for each individual menu item

    Parameters :

    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   07/26/96 Donncha_h1          Creation
--------------------------------------------------------------------------*/
int inGetFieldWidth(void) {
    /** /pdebug(("--inGetFieldWidth--"));*/

    switch (obDisp.inTerminalType) {
    case TERMINAL_OMNI_3200:
        return(20);
    default:
        return(6);
    }
}



void SetItemText(char* szItemText,char* szLine1,char* szLine2,int inItemNum) {
    int inFirstCharIndex,
    inNumChars;
    int inFieldWidth;

    /** /pdebug(("--SetItemText--"));*/

    inFieldWidth = inGetFieldWidth();
    inFirstCharIndex = --inItemNum * inFieldWidth;

    szLine1 += inFirstCharIndex;
    for (inNumChars = 0; inNumChars < inFieldWidth - 1; ++inNumChars) {
        if ((*szItemText == '@') && (szItemText[1] == '@'))
            ++szItemText;
        else if ((*szItemText == '\0') || (*szItemText == '@'))
            break;
        *++szLine1 = *szItemText++;
    }
    while ((*szItemText != '\0') && (*szItemText != '@'))
        ++szItemText;

    /*
     * Write into the second line.
     */
    if ((*szItemText == '@') && (szItemText[1] != '@'))
        if (*++szItemText == ' ')
            ++szItemText;
    szLine2 += inFirstCharIndex;
    for (inNumChars = 0; inNumChars < inFieldWidth - 1; ++inNumChars) {
        if ((*szItemText == '@') && (szItemText[1] == '@'))
            ++szItemText;
        else if ((*szItemText == '\0') || (*szItemText == '@'))
            break;
        *++szLine2 = *szItemText++;
    }
}

/*-------------------------------------------------------------------------
    Function :  vdUpdateMenus
    Description :
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0      ?         ?                         ?
      1   11/21/96 Donncha_h1 The O392 menu now starts from postion 1
--------------------------------------------------------------------------*/
void vdUpdateMenu() {
    char szScrap[MESSAGE_SIZE + 1];
    char szRJust[MESSAGE_SIZE + 1];
    char szItemText[4][21 + 1];
    char szPrompt[2 + 1];

    int inIndex;
    int inRemainingItems;
    MenuItem* pmeDisplayItem;

    int inCaratLine = 4;
    int inPutCarat = 0;
    int inLineIncr = 1;
    int inLineLimit = 0;
    int inFirstLine = 1;
    static int inProcFs = 0;
    char pchFmt[10];

    switch (obDisp.inCharsPerRow) {
        // added__ML__03032000
    case 21:
        /*
           *  6x8 font
           */
        inCaratLine = 8;
        inLineLimit = obDisp.inCharsPerRow;
        inLineIncr = 2;
        strcpy(pchFmt, "%.21s");
        break;

    case 16:
        /*
         *  8x16 font
           */
        inCaratLine = 4;
        inLineLimit = obDisp.inCharsPerRow;
        inLineIncr = 1;
        strcpy(pchFmt, "%.2s%.14s");
        break;

    case 8:
        /*
           *  16x16 font
         */
        inCaratLine = 4;
        inLineLimit = obDisp.inCharsPerRow;
        inLineIncr = 1;
        strcpy(pchFmt, "%.1s%.7s");
        break;
    default:
        break;
    }

    if (inFirstScrollItem != ANY_KEY) {
        /*
         * Figure out how many menu items
         * remain to be displayed.
         */
        inRemainingItems = inNumScrollingMenuItems - inCurrentScrollItem;
        /*
         * We need both of the following tests for the following reason:
         *    1.  First, we make sure that the menu is spread out over
         *        several pages so we can leave space for the "More" arrow...
         *    2.    Second, we make sure that we have enough menu items
         *        left over...
         *    ...THEN we limit the number of items remaining to be displayed
         *        to the rest of the page.
         */

        obDisp.blCaratVis = VS_TRUE;

        if (inNumScrollingMenuItems <= ITEMS_PER_FIRST_PAGE)
            obDisp.blCaratVis = VS_FALSE;

        pmeDisplayItem = &pmeScrollItem[inCurrentScrollItem - 1];

        if ((inNumScrollingMenuItems > NUM_ITEMS_PER_PAGE) && (inRemainingItems >= NUM_ITEMS_PER_PAGE))
            inRemainingItems = NUM_ITEMS_PER_PAGE;

        if (inFirstScreen(pmeDisplayItem + 1)) {
            /*
             *  On 3200, first root
             *  screen has 3 items.
             */
            inProcFs = 1;     /* signify firstscreen processed */
            inFirstMenuKey = KEY_f; /* disable key_e on first screen */

            inFirstLine = inFirstLn() + inLineIncr; /* time/date appear on line 1 */

            inNoDisp = 0;  /* turn-on datetime in appl_idle_loop */

            if (lnCurrentMenuTitle) {
                int inTitleColumn = 0;
                char szMenuTitle[MESSAGE_SIZE + 1];

                /*
                 * Change the title if menu has one.
                 */
                vdGetMessageFromFile(lnCurrentMenuTitle, szMenuTitle);
                if ((inTitleColumn = obDisp.inCharsPerRow / 2 - strlen(szMenuTitle) / 2) < 1)
                    inTitleColumn = 1;
                vdClearTitleLine();
                vdDisplayAt(inTitleColumn, obDisp.inTitleLine, szMenuTitle, CLR_EOL);
            }
        } else {
            inProcFs = 0;
            inFirstMenuKey = KEY_e;
            inFirstLine = inFirstLn();
            /*
             * turn-off datetime
             */
            inNoDisp = 1;
        }

        /*
         * Get the menu text from the message file.
         */
        szItemText[0][0] = NULL_CH;
        szItemText[1][0] = NULL_CH;
        szItemText[2][0] = NULL_CH;
        szItemText[3][0] = NULL_CH;

        for (inIndex = 0; ((inIndex < 4) && (inIndex < inRemainingItems)); ++inIndex) {
            ++pmeDisplayItem;
            if ((pmeDisplayItem)->mlTitleID > 0L) {
                vdGetMessageFromFile(pmeDisplayItem->mlTitleID, szScrap);
                memset(szRJust, NULL_CH, sizeof(szRJust));

                if (inIndex == 3)
                    switch (shGetFontType()) {
                        //__ML_03032000 switch based on the font type
                    case FONT_TYPE_NORMAL:
                    case FONT_TYPE_GRAPHIC_1BYTE:
                        szScrap[inLineLimit] = NULL_CH;
                        pad(szRJust, szScrap, ' ', inLineLimit - 2, RIGHT);
                        break;
                    case FONT_TYPE_GRAPHIC_2BYTE:
                        szScrap[inLineLimit * 2] = NULL_CH;
                        vdMlPadChar(szRJust, szScrap, (inLineLimit) * 2, ML_RIGHT, ' ');
                    default:
                        break;
                    }
                else
                    switch (shGetFontType()) {
                        //__ML__03032000 switch based on the font type
                    case FONT_TYPE_NORMAL:
                    case FONT_TYPE_GRAPHIC_1BYTE:
                        szScrap[inLineLimit] = NULL_CH;
                        pad(szRJust, szScrap, ' ', inLineLimit, RIGHT);
                        break;
                    case FONT_TYPE_GRAPHIC_2BYTE:
                        szScrap[inLineLimit * 2] = NULL_CH;
                        vdMlPadChar(szRJust, szScrap, (inLineLimit) * 2, ML_RIGHT, ' ');
                    default:
                        break;
                    }
		
                if (obDisp.inCharsPerRow == 21)
                    sprintf(szItemText[inIndex], pchFmt, szRJust);
                else {
                    if (inIndex < 3) {
                        if ((inIndex + 1) == inRemainingItems)
                            inPutCarat = 1;
                        else
                            inPutCarat = 0;
                    } else
                        inPutCarat = 1;

                    if (inIndex == 3) {
                        if (shGetFontType() == FONT_TYPE_GRAPHIC_2BYTE) {
                            //__ML__06032000
                            sprintf(szItemText[inIndex], "%.16s", szRJust);
                        } else {
                           strlcpy(szPrompt, "  ", (sizeof(szPrompt) - 1)); 
                           sprintf(szItemText[inIndex], pchFmt, szPrompt, szRJust);
                            
                            
                        }
                    } else {
                        if (shGetFontType() == FONT_TYPE_GRAPHIC_2BYTE) {
                            //__ML__06032000
                            sprintf(szItemText[inIndex], "%.16s", szRJust);
                        } else
                            sprintf(szItemText[inIndex], "%.16s", szRJust);
                    }
                }
            }
        }

        /*
         * Now display the menu text;
         * up to 20 chars.
         */
        vdClearNonTitleLines();
	 vdDisplayAt(obDisp.inHomeCol, inFirstLine, szItemText[0], CLR_EOL);
	 vdDisplayAt(obDisp.inHomeCol, inFirstLine + inLineIncr, szItemText[1], CLR_EOL);
	vdDisplayAt(obDisp.inHomeCol, inFirstLine + (2 * inLineIncr), szItemText[2], CLR_EOL);

        if (!inProcFs) {
            /*
             *  display 4th item
             *  if not first screen
             */
            //vdDisplayAt(obDisp.inHomeCol, inFirstLine+(3*inLineIncr), szItemText[3], NO_CLEAR);
            // Multi-Lang Bug fix for ASPAC
            if ((getgrid() == 0) && (get_font_mode() == 2)) {
                /* Chinese Language */
		vdDisplayAt(obDisp.inHomeCol, inFirstLine + (3 * inLineIncr), szItemText[3], CLR_EOL); 
				  
            } else {
/* LIEM because this not work ok
                 char szTmp[22];
                 vdTrimLeadSpaces(szItemText[3]);
                 memset(szTmp,0x00,sizeof(szTmp));
		   memcpy(szTmp,szItemText[3],strlen(szItemText[3]));			 
		   memset(szItemText[3],0x20,22);		 
		   memcpy(&szItemText[3][21-strlen(szTmp)],szTmp,strlen(szTmp));
		   szItemText[3][21]=0x00;
*/
		   vdDisplayAt(obDisp.inHomeCol, inFirstLine + (3 * inLineIncr), szItemText[3], NO_CLEAR);
		  /* English version, use original coding */
		  //vdDisplayAt(obDisp.inHomeCol, inFirstLine + (3 * inLineIncr), szItemText[3], NO_CLEAR); // jrd
					
            }
        }


        if (obDisp.inCharsPerRow == 21)
        {
		/* needs different bitmap; let go for now 9/3/98 */
            //vdDisplayAt(obDisp.inHomeCol, inCaratLine, CARAT, CLR_EOL);
            //if (inPutCarat) {
                gotoxy(obDisp.inHomeCol, inCaratLine);

                if (obDisp.blCaratVis)
                {
		      // Rannie_B1 04262004: Fixed the bug wherein the down arrow icon is not shown
		      // if the language in use is not English
                    //vdDisplayFontChar(UTILITY_FONT, obDisp.chCaratOffset);
                    vdMLDisplayFontChar(UTILITY_FONT, obDisp.chCaratOffset, obDisp.inHomeCol, inCaratLine);
                    // End Rannie_B1 04262004
		  }
                else
                    vdWriteSpace();
            //}
			
        }
        else

        {
            if (inPutCarat) {
                gotoxy(obDisp.inHomeCol, inCaratLine);

                if (obDisp.blCaratVis)
                {
		      // Rannie_B1 04262004: Fixed the bug wherein the down arrow icon is not shown
		      // if the language in use is not English
                    //vdDisplayFontChar(UTILITY_FONT, obDisp.chCaratOffset);
                    vdMLDisplayFontChar(UTILITY_FONT, obDisp.chCaratOffset, obDisp.inHomeCol, inCaratLine);
                    // End Rannie_B1 04262004
		  }
                else
                    vdWriteSpace();
            }
        }
    }
} /* end vdUpdateMenu() */

static int inFirstScreen(MenuItem* pmeDisplayItem) {
    if ((pmeDisplayItem->miItemKey == ANY_KEY) && (pmeDisplayItem->mlTitleID == MenuList[inFirstScrollItem].meItem.mlTitleID) && (pmeDisplayItem->miFuncIndex == MenuList[inFirstScrollItem].meItem.miFuncIndex) && (pmeDisplayItem->miSubFuncIndex == MenuList[inFirstScrollItem].meItem.miSubFuncIndex))
        return(1);
    else
        return(0);
}

/* Any Calls to lnAllocateMenu() must be followed by a vdFree(MenuList) */
/* This Routine allocates memory from the heap - Take Notice */

typedef int (*PFI_PSZ_INT)(char*,int);

static long lnAllocateMenu(void) {
    int inLoadedFine = FALSE;
    int inMenuFile;
    long lMenuSize,
    lnErrorNumber;
    char szMenusFileName[FILENAME_SIZE + 1];

    enum errCODES {
        NO_ERR, READ_ERR, ALLOC_ERR, SEEKSET_ERR, SEEKEND_ERR, OPENMF_ERR, CLOSEMF_ERR, GETNM_ERR
    };

    int inCloseRet = 0;
    long lnRet = (long) NO_ERR;

    PFI_PSZ_INT pinTempFn;

    /** /pdebug(("--lnAllocateMenu()--"));*/

    lnErrorNumber = MENU_FILE_ERR_MSG;

    if ((pinTempFn = inGetFunctionPointer(GET_MENU_FILE_NAME)) == NULL_PFI)
        return(VS_ERR);

    if (pinTempFn(szMenusFileName, sizeof(szMenusFileName)) == VS_SUCCESS) {
        if ((inMenuFile = open(szMenusFileName, O_RDONLY)) != -1) {
            lnErrorNumber = MENU_SIZE_ERR_MSG;
            if ((lMenuSize = lseek(inMenuFile, 0L, SEEK_END)) != -1L) {
                lnErrorNumber = MENU_SEEK_ERR_MSG;
                if (lseek(inMenuFile, (long) GEN_VER_SIZE, SEEK_SET) != -1L) {
                    lMenuSize -= GEN_VER_SIZE;
                    lnErrorNumber = MENU_ALLOC_ERR_MSG;
                    if ((MenuList = (MenuElement *) pchAlloc((unsigned) lMenuSize)) != NULL_CH) {
                        lnErrorNumber = MENU_READ_ERR_MSG;
                        if (read(inMenuFile, (char *) &MenuList[0], (int) lMenuSize) == lMenuSize)
                            inLoadedFine = TRUE;
                        else {
                            vdFree((char *) MenuList);
                            MenuList = NULL_CH;
                            lnRet = (long) READ_ERR;
                        }
                    } else
                        lnRet = (long) ALLOC_ERR;
                } else
                    lnRet = (long) SEEKSET_ERR;
            } else
                lnRet = (long) SEEKEND_ERR;

            inCloseRet = close(inMenuFile);
            if (inCloseRet)
                lnRet = (long) CLOSEMF_ERR;
        } else
            lnRet = (long) OPENMF_ERR;
    } else
        lnRet = (long) GETNM_ERR;

    if (inLoadedFine == FALSE) {
        vdWarnBeep();
        vdWarnBeep();
        vdDisplayMessageFromFile(lnErrorNumber, ERROR_MSG);
    }

    return(lnRet);
}

void vdSelectMenu(int inMenuNum) {
    int inPrevIndex = 0,
    inPrevMenu = 0;
    long lnRes = 0L;
    static int inCntr = 0;

    /** /pdebug(("--vdSelectMenu(%d)--", inMenuNum));*/
    //lnRes = lnAllocateMenu();     KAV - done in vdInitMenus()

    if (pmeCurrentMenu != NULL) {
        inPrevIndex = inCurrentMenuIndex;
        inPrevMenu = pmeCurrentMenu->mMenuIdentifier;
    }

    inCurrentMenuIndex = inGetIndexForMenu(inMenuNum);
    if (inCurrentMenuIndex > 0) {
        pmeCurrentMenu = &MenuList[inCurrentMenuIndex].meMenu;

        /*
         * Find the first menu item that's part of the scroll list.
         */
        pmeScrollItem = (MenuItem *) pmeCurrentMenu;
        inFirstScrollItem = inCurrentMenuIndex + 1;
        inNumScrollingMenuItems = pmeCurrentMenu->mNumMenuItems + 1;
        while (--inNumScrollingMenuItems && ((++pmeScrollItem)->miItemKey != ANY_KEY))
            ++inFirstScrollItem;

        /*
         *      Calculate # of items on last menu screen.
         */
        if (inNumScrollingMenuItems < ITEMS_PER_PAGE)
            inNumberOfItemsAtEnd = 0;
        else if (inNumScrollingMenuItems < 6)
            inNumberOfItemsAtEnd = (inNumScrollingMenuItems) % ITEMS_PER_FIRST_PAGE;
        else
            inNumberOfItemsAtEnd = (inNumScrollingMenuItems - ITEMS_PER_FIRST_PAGE) % ITEMS_PER_PAGE;

        pmeScrollItem = &MenuList[inFirstScrollItem].meItem;

        /*
         * Set the scroll list vars to -1 if no items are to be
         * in a scrolling list.
         */
        if (inNumScrollingMenuItems <= 0)
            inFirstScrollItem = -1;
        inCurrentScrollItem = 0;

        lnCurrentMenuTitle = pmeCurrentMenu->mMenuTitle;
        obDisp.vdDO_UpdateMenu();
    }
}

/*-------------------------------------------------------------------------
    Function :    inEventResponder()
    Description :
    Parameters :    inEventCode - event that idle engine has trapped
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1   11/07/96 Page_K1    Close Folio port at beginning and reopen at
                                end of event if not PININ
      2   11/11/96 Page_K1    Change #ifdef FOLIO to check inPINPadType
      3   12/06/96 Donncha_H1 Removed #ifdef DEBIT and now checks the debit flag
      4   12/19/97 Page_K1    Remove check on FOLIO pinpad
      5   01/11/99 Monique_B1 Fix 3200 bug which skipped last main menu item if
                              inNumberOfItemsAtEnd = 0.
--------------------------------------------------------------------------*/
int inEventResponder(int inEventCode) {
    int inFunctionOffset,
    inIndex,
    inResult = BRANCH_EXIT,
    inCurrentMenuId;
    MenuItem* pmeMenuItem;
    int inExplicitRet = BRANCH_EXIT;
    int inLastMenu = 0;

	{//LIEM ADD: LOCK KEY and BACKLIGHT CONTROL
		if (((inEventCode >= KEY_e)  && (inEventCode <= KEY_d)) || 
			((inEventCode >= KEY_0) && (inEventCode <= 255))){
			if (inEventCode == KEY_CANCEL){
			} else if (inImamUnlockKeyboard == 0){  //keyboard still locked
				clrscr();
				write_at(" Press  -ENTER- ", 16, 1, 2);
				write_at("and Then -ALPHA-", 16, 1, 3);
				pause(150);
				inEventCode = KEY_CANCEL;
				//return(BRANCH_EXIT);
			} 
		}
	}

    /* ====> CBS 10-13-99 */
    disable_hot_key();
    /* <==== CBS 10-13-99 */

    /*LeeChyi - 21092005: Added
    	For power saving, turn turn on the backlight after a key press
  	*/
    // set_backlight(VS_TRUE); //LIEM DISABLE IT AS WE HAVE OUR OWN Display Control

    //pdebug(("inEventResponder = %d", inEventCode));

    inCurrentMenuId = pmeCurrentMenu->mMenuIdentifier;

    /*
     * Look for the matching event.
     */
    inLastMenu = ((MenuElement *) pmeCurrentMenu)->meMenu.mMenuIdentifier;
    pmeMenuItem = (MenuItem *) pmeCurrentMenu + 1;
    for (inIndex = 0; inIndex < pmeCurrentMenu->mNumMenuItems; ++inIndex, ++pmeMenuItem) {
        if (pmeMenuItem->miItemKey == inEventCode)  /* This event is what we're looking for! */ {
            if (pmeMenuItem->miFuncIndex > 0)       /* The user has selected some function */ {
                if (pmeMenuItem->miReDisplayMenu != NO_MENU_DISPLAY) {
                    pdebug(("pmeMenuItem->miReDisplayMenu=%d", pmeMenuItem->miReDisplayMenu));
                    /*
                         * Clear screen in big font mode to remove junk chars that remain
                         * at bottom-right of screen when we change to small font
                         */
                    clrscr();
                    vdSetActionFont();
                }
                if (pmeMenuItem->mlTranMsg)
                {
                    vdDisplayTranTitle(pmeMenuItem->mlTranMsg);
                    #ifdef VXEMVAPP
                    		lnTranTitleMessage = pmeMenuItem->mlTranMsg;
                    #endif /* VXEMVAPP */
                }
                if (inGetPwdFromUser(pmeMenuItem->miPasswordLevel, pmeMenuItem->miPITIndex) == VS_SUCCESS)
                    inResult = inOperations(pmeMenuItem->miFuncIndex, pmeMenuItem->miSubFuncIndex, pmeMenuItem->mlTranMsg);
                if (pmeMenuItem->miReDisplayMenu != NO_MENU_DISPLAY) {
                    pdebug(("pmeMenuItem->miReDisplayMenu=%d", pmeMenuItem->miReDisplayMenu));
                    vdSetMenuFont();
                    vdSelectMenu(ROOT_MENU_ID);
                }
                enable_hot_key();
                return(BRANCH_EXIT);
            } else                                    /* The user has selected a sub-menu */ {
                /*
                   * Clear screen in big font mode to remove junk chars that remain
                 * at bottom-right of screen when we change to small font
                   */
                clrscr();
                vdSetActionFont();
                if (inGetPwdFromUser(pmeMenuItem->miPasswordLevel, pmeMenuItem->miPITIndex) == VS_SUCCESS) {
                    vdSetMenuFont();
                    vdSelectMenu(pmeMenuItem->miFuncIndex);
                } else {
                    vdSetMenuFont();
                    vdSelectMenu(ROOT_MENU_ID);   /* Return to idle if failed */
                }
            }
            enable_hot_key();
            return(inResult);
        }
    }

    /*
     * We got here because the user event wasn't found in the
     * menu item list. So now we check to see if the user selected
     * a menu item via the auto menu mechanism (i.e., with scrolling,
     * displaying, etc. done by the system).
     */
    if (inEventCode == KEY_CANCEL)  // BJD: KEY_CLR -> KEY_CANCEL
    {
        vdSetMenuFont();
        fDisplayLogoNow = VS_TRUE;
        vdSelectMenu(ROOT_MENU_ID);
#ifdef PINPAD_DEFINED
        if (inGetPINPadType() != NO_PINPAD)
            obPinPad.vdSendAbortToPINPad();
#endif /* PINPAD_DEFINED */
    } else if (inEventCode == KEY_BS) {
        if (obDisp.inTerminalType == TERMINAL_OMNI_3200) {
            while (KBHIT())
                get_char(); /* flush it out.... */
            vdToggleArrow();
        }
    } else if (inFirstScrollItem != -1) {
        /*
         * The current menu has a displayed menu list.
         * First, if there are enough menu items to require scrolling
         * through it, and the user presses the scroll key, then we scroll.
         */
        if ((inNumScrollingMenuItems > ITEMS_PER_FIRST_PAGE) && ((inEventCode == inScrollLeftKey) || (inEventCode == inScrollRightKey))) {
            /*
             * Scroll through the list.
             */
            if (inEventCode == inScrollLeftKey) {
                inCurrentScrollItem -= NUM_ITEMS_PER_PAGE;

                // Attempting to scroll backward to first screen
                if (inCurrentScrollItem == -1)
                    inCurrentScrollItem = 0;
                // Attempting to scroll backward to last screen
                if (inCurrentScrollItem < 0)
                    inCurrentScrollItem = inNumScrollingMenuItems - (inNumberOfItemsAtEnd > 0 ? inNumberOfItemsAtEnd : NUM_ITEMS_PER_PAGE);
            } else {
                inCurrentScrollItem += NUM_ITEMS_PER_PAGE;

                // Attempting to scroll forward to first screen
                if (inCurrentScrollItem >= inNumScrollingMenuItems)
                    inCurrentScrollItem = 0;
            }
            obDisp.vdDO_UpdateMenu();
        } else if ((inFirstMenuKey <= inEventCode) && (inEventCode <= inLastMenuKey)) {
            /*
             * The user has chosen a menu item.
             */
            if (inDisplayLeftToRight)
                inFunctionOffset = inEventCode - inFirstMenuKey;
            else
                inFunctionOffset = inLastMenuKey - inEventCode;
            if ((inCurrentScrollItem + inFunctionOffset) < inNumScrollingMenuItems) {
                MenuItem* pmeChosenItem;

                pmeChosenItem = &pmeScrollItem[inCurrentScrollItem + inFunctionOffset];

                /*
                 * Clear screen in big font mode to remove junk chars that remain
                 * at bottom-right of screen when we change to small font
                 */
                clrscr();

                if (pmeChosenItem->miFuncIndex > 0) {
                    vdSetActionFont();
                    if (pmeChosenItem->mlTranMsg) {
                        clrscr();
                        vdDisplayTranTitle(pmeChosenItem->mlTranMsg);
                        #ifdef VXEMVAPP
                    		lnTranTitleMessage = pmeChosenItem->mlTranMsg;
                    	   #endif /* VXEMVAPP */
                    }
                    if (inGetPwdFromUser(pmeChosenItem->miPasswordLevel, pmeChosenItem->miPITIndex) == VS_SUCCESS)
                        inResult = inOperations(pmeChosenItem->miFuncIndex, pmeChosenItem->miSubFuncIndex, pmeChosenItem->mlTranMsg);
                    vdSetMenuFont();
                    if (pmeChosenItem->miReDisplayMenu) {
                        clrscr();
                        vdSelectMenu(inCurrentMenuId);
                    } else
                        vdSelectMenu(ROOT_MENU_ID);
                } else {
                    vdSetActionFont();
                    if (inGetPwdFromUser(pmeScrollItem[inCurrentScrollItem + inFunctionOffset].miPasswordLevel, pmeScrollItem[inCurrentScrollItem + inFunctionOffset].miPITIndex) == VS_SUCCESS) {
                        vdSetMenuFont();
                        vdSelectMenu(pmeChosenItem->miFuncIndex);
                    } else {
                        vdSetMenuFont();
                        vdSelectMenu(ROOT_MENU_ID);  /* Return to idle if failed */
                    }
                }
            } else
                vdBeep();
        }
        /*
         *      Event not in menu...
         */
        else {
            vdSetMenuFont();
            fDisplayLogoNow = VS_TRUE;
            vdSelectMenu(ROOT_MENU_ID);
        }
    }

    /** /pdebug(("inResult=%d",inResult));*/
    /* ====> CBS 10-13-99 */
    enable_hot_key();
    /* <==== CBS 10-13-99 */
    return(BRANCH_EXIT);
}

int inAKeyResponder() {
    /** /pdebug(("--inAKeyResponder--"));*/
	vdImamDisplayMenu(3);
    return(inEventResponder(KEY_a));
}

int inBKeyResponder() {
    /** /pdebug(("--inBKeyResponder--"));*/
    return(inEventResponder(KEY_b));
//	return(inImamActionIDEventResponder(IMAMM_WIRELESS_STATUS)); //
}

int inCKeyResponder() {
    /** /pdebug(("--inCKeyResponder--"));*/
    return(inEventResponder(KEY_c));
}

int inDKeyResponder() {
    /** /pdebug(("--inDKeyResponder--"));*/
    return(inEventResponder(KEY_d));
}

int inImamF0KeyResponder() {
	int inImamAction = 0;

	if (inImamTerminalModel == 670){
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem);
		//return 0;
	} else {
		return 0;
	}
	if (inImamAction==0){
#ifdef KEY_F0
		return(inEventResponder(KEY_F0));
#else
		return 0;
#endif
	} else {
		return(inEventResponder(inImamAction));
	}
}

int inEKeyResponder() {
	int inImamAction = 0;

	if (inImamTerminalModel == 670){
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem+1);
	} else {
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem);
	}

	if (inImamAction==0){
		return(inEventResponder(KEY_e));
	} else {
		return(inEventResponder(inImamAction));
	}
}

int inFKeyResponder() {
	int inImamAction = 0;

	if (inImamTerminalModel == 670){
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem + 2);
	} else {
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem + 1);
	}
	if (inImamAction==0){
		return(inEventResponder(KEY_f));
	} else {
		return(inEventResponder(inImamAction));
	}
}

int inGKeyResponder() {
	int inImamAction = 0;

	if (inImamTerminalModel == 670){
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem + 3);
	} else {
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem + 2);
	}
	if (inImamAction==0){
		return(inEventResponder(KEY_g));
	} else {
		return(inEventResponder(inImamAction));
	}
}

int inHKeyResponder() {
	int inImamAction = 0;

	if (inImamTerminalModel == 670){
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem + 4);
	} else {
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem + 3);
	}
	if (inImamAction==0){
		return(inEventResponder(KEY_h));
	} else {
		return(inEventResponder(inImamAction));
	}
}

int inImamF5KeyResponder() {
	int inImamAction = 0;

	if (inImamTerminalModel == 670){
		inImamAction = inImamProcessTrans(lnImamMenuItem=lnImamMenuItem + 5);
	} else {
		return 0;
	}
	if (inImamAction==0){
#ifdef KEY_F5
		return(inEventResponder(KEY_F5));
#else
		return 0;
#endif
	} else {
		return(inEventResponder(inImamAction));
	}
}

int in0KeyResponder() {
    /** /pdebug(("--in0KeyResponder--"));*/
    return(inEventResponder(KEY0));
}

int in1KeyResponder() {
    /** /pdebug(("--in1KeyResponder--"));*/
    return(inEventResponder(KEY1));
}

int in2KeyResponder() {
    /** /pdebug(("--in2KeyResponder--"));*/
    return(inEventResponder(KEY2));
}

int in3KeyResponder() {
    /** /pdebug(("--in3KeyResponder--"));*/
    return(inEventResponder(KEY3));
}

int in4KeyResponder() {
    /** /pdebug(("--in4KeyResponder--"));*/
    return(inEventResponder(KEY4));
}

int in5KeyResponder() {
    /** /pdebug(("--in5KeyResponder--"));*/
    return(inEventResponder(KEY5));
}

int in6KeyResponder() {
    /** /pdebug(("--in6KeyResponder--"));*/
    return(inEventResponder(KEY6));
}

int in7KeyResponder() {
    /** /pdebug(("--in7KeyResponder--"));*/
    return(inEventResponder(KEY7));
}

int in8KeyResponder() {
    /** /pdebug(("--in8KeyResponder--"));*/
    return(inEventResponder(KEY8));
}


int in9KeyResponder() {
    /** /pdebug(("--in9KeyResponder--"));*/
    return(inEventResponder(KEY9));
}

int inStarKeyResponder() {
    /** /pdebug(("--inStarKeyResponder--"));*/
    return(inEventResponder(KEY_STR));
}

int inPoundKeyResponder() {
    /** /pdebug(("--inPoundKeyResponder--"));*/
    return(inEventResponder(KEY_PND));
}

int inCancelKeyResponder() {
    /** /pdebug(("--inCancelKeyResponder--"));*/
	vdImamDisplayMenu(2);
    return(inEventResponder(KEY_CANCEL));
}

int inBackSpaceKeyResponder() {
    /** /pdebug(("--inBackSpaceKeyResponder--"));*/
    return(inEventResponder(KEY_BS));
}

int inAlphaKeyResponder() {
    /** /pdebug(("--inAlphaKeyResponder--"));*/
    return(inEventResponder(KEY_ALP));
}


int inEnterKeyResponder() {
    int inTimerKeyPress;
    int inKeyPress;
#ifndef IMAM_REMOVE
    inTimerKeyPress = 5;

   	/*LeeChyi - 21092005: Added
    For power saving, turn turn on the backlight after a key press
  */
    set_backlight(VS_TRUE);

    /** /pdebug(("--inEnterKeyResponder--"));*/
    if (inCurrentMenuIndex == ROOT_MENU_INDEX) {
	 disable_hot_key();		//meca 20040823 -- to fix SPQALog0030
        clrscr();
        vdDispMsgCentered(FUNCTIONS_TITLE_MSG, obDisp.inTitleLine, CLR_EOL);
        do {
            /* Note that the return is either a key-press or KEY_CLR in the case */
            /* of a time-out occurring.                                          */
            inKeyPress = inWaitKey(inTimerKeyPress);
            switch (inKeyPress) {
            case KEY0:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_0));

            case KEY1:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_1));

            case KEY2:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_2));

            case KEY3:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_3));

            case KEY4:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_4));

            case KEY5:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_5));

            case KEY6:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_6));

            case KEY7:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_7));

            case KEY8:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_8));

            case KEY9:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_9));

            case KEY_CANCEL:
                enable_hot_key();
                return(inEventResponder(KEY_CANCEL)); // BJD: KEY_CLR -> KEY_CANCEL

            case KEY_STR:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_STR));

            case KEY_PND:
                enable_hot_key();
                return(inEventResponder(KEY_FUNC_PND));
            default:
                ERR_BEEP();
                break;
            }
        } while (TRUE);
    } else
        return(inEventResponder(KEY_CR));
#else 
	return VS_SUCCESS;
#endif
}


int inCardResponder() {
    if ((CHK_CARD_RDR()) || (inVMACCardSelect)) {
#ifndef IMAM_PERMATA
		return (inImamCardResponder()); //
#else
        return(inEventResponder(APPL_CARD));
#endif
    } else {
        vdDisplayMessageFromFile(CARDREAD_ERR_MSG, WARNING_MSG);
        return(BRANCH_EXIT);
    }
}

int inModemInResponder() {
    /** /pdebug(("--inModemInResponder--"));*/
    return(inEventResponder(MDMIN));
}

/*
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1   11/18/96  Page_K1   If not FOLIO return BRANCH_EXIT.
      2   12/19/97  Page_K1   Remove FOLIO check
      3   05/15/98 Kevin_V1   Convert to CheckReader support.
*/
int inPinInResponder() {
    int inRetVal = BRANCH_EXIT;

    /** /pdebug(("--inPinInResponder--"));*/
    if (srGDS.inChkrdrPort == PININ)
        inRetVal = inEventResponder(PININ);

    return inRetVal;
}

int inC1_InResponder() {
    int inRetVal = BRANCH_EXIT;
/*
    if (srGDS.inChkrdrPort == C1_IN) {
        srGDS.fCheckSwipeFromIdle = VS_TRUE;
        inRetVal = inEventResponder(C1_IN);
        srGDS.fCheckSwipeFromIdle = VS_FALSE;
    }
*/
//	inImamDoPinpadRecvProcessSend();
    return inRetVal;
}

int inC2_InResponder() {
int  inRetVal = BRANCH_EXIT;

	//inImamDoPinpadRecvProcessSend();

    return inRetVal;
}

int inC3_InResponder() {
    /** /pdebug(("--inC3_InResponder--"));*/
    srGDS.fResetIdleTimer = VS_FALSE;
    return(inEventResponder(C3_IN));
}
typedef int (*PFI_SHORT) (short );
/****************************************************************************
*   NAME        : inAppl_activate
*   INPUTS      : NONE
*   RETURNS     : 0
*   DESCRIPTION : Handler for activate event.
*                 Perform all necessary opens and initializations
*                 in order to reactivate this application.
*   NOTES       : Currently the Printer and Card Reader are tested for an open
*                 condition. If closed, they are opened again prior to application
*                 activation.
******************************************************************************/
short inAppl_activate()
{
	#ifdef CHECK_DEFINED
  	 CCT_REC srCCTRecLocal;
	#endif
	
    int inResult;
    PFI_SHORT inPinPadSetup = (PFI_SHORT) NULL; /* vsk -- added custom initialisation of Pinpad */

#ifdef CASHCARD_DEFINED
      int inPinpadType = 0;		//meca 20041023 -- for cashcard using SAM
#endif //CASHCARD_DEFINED

	event_t lnEvent;

	int inEESLAPIReturnValue;

	   //jrd one source
    #ifdef __arm
     unsigned short ushEventDataSize = 0;
    #endif
    #ifdef _TARG_68000
     unsigned int ushEventDataSize = 0;
    #endif

	
	unsigned short ushEESLAPIReturnValue = 0;

	VS_BOOL fExitCondition = VS_FALSE;

	char szLogicalName[16];
	unsigned char szEventDataBuffer[512];

	#if 1 //ATS Bug Fix 35
	if (inMAMAvailable)
	{
		if (lnAppActivateEvent != 999L)
		{
			LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Sending release devices event"));

			inEESLAPIReturnValue = EESL_send_event("DEVMAN", ICICI_RELEASE_DEVICES, NULL, 0);
			while(inEESLAPIReturnValue != 0)
			{
				SVC_WAIT(200);
				inEESLAPIReturnValue = EESL_send_event("DEVMAN", ICICI_RELEASE_DEVICES, NULL, 0);
			}

			while (!fExitCondition)
			{
				LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Waiting for response from DEVMAN"));

				if (EESL_queue_count() == 0)
				{
					while ((lnEvent = wait_event()) != EVT_PIPE)
					{
						SVC_WAIT(0);
					}
				}

				if (EESL_queue_count() != 0)
				{
					ushEESLAPIReturnValue = EESL_read_cust_evt(	szEventDataBuffer, sizeof(szEventDataBuffer),
															&ushEventDataSize, szLogicalName);

					LOG_PRINTFF((EESL_DEBUG_GLOBAL, "EESL_read_cust_evt() %u %s %u %s",
									ushEESLAPIReturnValue, szEventDataBuffer, ushEventDataSize, szLogicalName));

					if (ushEESLAPIReturnValue == ICICI_RELEASE_DEVICES)
					{
						LOG_PRINTFF((EESL_DEBUG_GLOBAL,"DEVMAN returned ICICI_RELEASE_DEVICES"));
						fExitCondition = VS_TRUE;
					}

					if (ushEESLAPIReturnValue == APP_RES_SET_UNAVAILABLE)
					{
						SVC_WAIT(800);
						LOG_PRINTFF((EESL_DEBUG_GLOBAL,"DEVMAN returned APP_RES_SET_UNAVAILABLE"));

						inEESLAPIReturnValue = EESL_send_event("DEVMAN", ICICI_RELEASE_DEVICES, NULL, 0);
						while(inEESLAPIReturnValue != 0)
						{
							SVC_WAIT(200);
							inEESLAPIReturnValue = EESL_send_event("DEVMAN", ICICI_RELEASE_DEVICES, NULL, 0);
						}
					}
				}
			}
		}
	}

#endif /*0*/

//meca 20041023 -- fix from cashcard O3750
	disable_hot_key();			//meca 20040321 -- disable the hot key until the process is complete
	
	// alvin_m1 -To ensure that resources are acquired only when EVENT is from Event Manager (?-assumption)
	// This is to fix the F2-F4 wrong password
	if(F2_F4_Flag != VS_TRUE)
	{
	       //EESL_send_devman_event("SOFTPAY", ACT_EVENT, NULL, 0); //uncommented this part to resolve the issue for stand alone jrd 04262005
		//return(BRANCH_EXIT);
	}
	F2_F4_Flag = VS_FALSE;
	// end alvin_m1
//meca 20041023 -- fix from cashcard O3750

    if (fGetEnablePrinter()) {
        //pdebug (("PCTEnablePrinter"));
        if (obPrinter.inHandle <= 0) {
            //pdebug (("inOpenPrinter"));
            inOpenPrinter();
            inSelectTemplateFile(&obPrinter);
            p350LinesPerInch(inGetP350LinesPerInch());
            p350ColumnMode(inGetP350ColMode());
        }
    }

    if (hCardReader <= 0)
        hCardReader = open(DEV_CARD, O_RDWR);

#ifdef ICC_DEFINED
    Init_CardSlot(CUSTOMER_CARD);
#endif

#ifdef CHECK_DEFINED
    /*  load CCT record in to local structure   */
    if (inLoadConfRec(CCT_FILE_NAME, SIZE_CCT_REC, 0, (char *) &srCCTRecLocal) == VS_SUCCESS)
        inResult = inInitCheckReader(VS_FALSE, &srCCTRecLocal);
#endif

#ifdef PINPAD_DEFINED

    //Setup appropriate function pointers in global PinPad object //vsk -- added custom initialisation of Pinpad
    if ((inPinPadSetup = inGetFunctionPointer(SETUP_PINPAD)) != NULL_PFI)
        inPinPadSetup(inGetPINPadType());
    else
        inSetupPinPad(inGetPINPadType());

//meca 20041023 -- for cashcard using SAM (start)
#ifdef CASHCARD_DEFINED
	if (gfPPadPresent)
	{
		inPinpadType = inGetPINPadType();

		switch(inPinpadType)
		{
	    		case SC455:
	    			inResult = inCASHInitializePinPad();	
	    			break;
	    		case IPP:
	    			inResult = inAS2805InitializePinPad();
	    			inAS2805SAMInit(CASH_ATR_APP_ID, CASH_ATR_APP_ID_LEN, CASH_ATR_APP_ID_OFFSET, VS_TRUE);
	    			inAS2805MutualAuth(); // This function will set the value of the global flag fGblMutualAuthSuccess
			   	if (fGblMutualAuthSuccess)
			   		if (inCashCheckKEK() == VS_SUCCESS)
			   			fGblAcqKEKLoaded = VS_TRUE;
	    			break;
	    		default:
	    			inResult = inInitializePinPad();
	    			break;
		}
	}
#else
	    if (gfPPadPresent)
	        inResult = inInitializePinPad();
#endif	//CASHCARD_DEFINED
//meca 20041023 -- for cashcard using SAM (end)

#endif	//PINPAD_DEFINED

    // load LCT record to avoid gabage menu on activate -- vsk Fixed garbage menu on VMAC switching
    inLoadLCTRec(inGetLanguageIdx());
    vdSetMenuFont();
    vdUpdateMenu();
    enable_hot_key() ;

	//ATS Bug Fix 35
	lnAppActivateEvent = 0L;
    return(BRANCH_EXIT);   // BJD: KEY_CLR -> KEY_CANCEL
}

#ifdef ICC_DEFINED

int inICC1Responder() {
    DWORD dwValue;
    RESPONSECODE rcRespCode;

    /** /pdebug(("--inICC1_InResponder--"));*/
    /* Select ICC1 : Tag 0x0190 */
    dwValue = CUSTOMER_CARD;
    rcRespCode = IFD_Set_Capabilities(Tag_Select_ICC, (BYTE *) (&dwValue));
    if (rcRespCode == IFD_Success) {
#ifndef IMAM_PERMATA
		return (inImamICC1Responder());
#else
        return(inEventResponder(ICC1_IN)); //
#endif
    } else {
        vdDisplayMessageFromFile(CARDREAD_ERR_MSG, WARNING_MSG);
        return(BRANCH_EXIT);
    }
}

int inICC2Responder() {
    DWORD dwValue;
    RESPONSECODE rcRespCode;

    /** /pdebug(("--inICC2_InResponder--"));*/
    /* Select ICC2 : Tag 0x0190 */
    dwValue = MERCHANT_FULL_SIZE_CARD;
    rcRespCode = IFD_Set_Capabilities(Tag_Select_ICC, (BYTE *) (&dwValue));
    if (rcRespCode == IFD_Success)
        return(inEventResponder(ICC2_IN));
    else {
        vdDisplayMessageFromFile(CARDREAD_ERR_MSG, WARNING_MSG);
        return(BRANCH_EXIT);
    }
}

#endif

/****************************************************************************
*   NAME        : inAppl_deactivate
*   INPUTS      : NONE
*   RETURNS     : FALSE
*   DESCRIPTION : Handler for deactivate event
*                 Perform all necessary closes and de-initializations
*                 in order to de-activate this application.
*   NOTES       : Currently the Printer and Card Reader are tested for an open
*                 condition. If open, they are closed again prior to application
*                 de-activation.
******************************************************************************/
short inAppl_deactivate() {
   
#ifdef CHECK_DEFINED
     int inResult;
#endif

#ifdef CASHCARD_DEFINED
	unsigned long ulSlotNo = MERCHANT_SLOT_1;
	int inNumSlot;
#endif //CASHCARD_DEFINED

    if (fGetEnablePrinter() && obPrinter.inHandle > 0) {
        close(obPrinter.inHandle);
        obPrinter.inHandle = -1;
    }
    if (hCardReader > 0) {
        close(hCardReader);
        hCardReader = -1;
    }

#ifdef ICC_DEFINED
    Close_CardSlot(CUSTOMER_CARD);
#endif

#ifdef CHECK_DEFINED
    inResult = inCloseCheckReader();
#endif

#ifdef PINPAD_DEFINED
	if (obPinPad.inHandle != -1) 
	{
		close(obPinPad.inHandle);
		obPinPad.inHandle = -1;/* vsk -- added custom initialisation of Pinpad and VMAC fix*/
	}

#ifdef CASHCARD_DEFINED	//meca 20041023 -- for cashcard using SAM
	for(inNumSlot = 0; inNumSlot < 4; inNumSlot++)
	{
		Close_CardSlot(ulSlotNo);
    		ulSlotNo = ulSlotNo << 1;
	}
#endif //CASHCARD_DEFINED

#endif	//PINPAD_DEFINED

//meca 20041023 -- fixed from cashcard O3750 -- for auto processing in multi-app environment
	srGDS.fSoftPayActive = VS_FALSE;			// Mark SoftPay as inActive
//meca 20041023 -- fixed from cashcard O3750 -- for auto processing in multi-app environment


    return BRANCH_EXIT;
}

/*-------------------------------------------------------------------------
    Function :  idle_exit
    Description :    Called by Application Idle Engine after each transaction.
    Parameters :
    Returns :
    Globals :
    Notes :
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      1   10/04/95  Eddy_B1      Eliminated HOSTZT pre-proc switch. Replaced w/ call
                              to inHostInitZontalk().
      2   10/11/95   T_Al_G      Added call to vdFlushCardBuffer().
      3   01/18/96  Henry_G1  Removed reference to inHostInitZontalk.
      4   11/17/98  Page_K1   If PP501 Reset PINPad idle
--------------------------------------------------------------------------*/

int idle_exit(int state) {
    

#ifdef CHECK_DEFINED
    int inResult;
    CCT_REC srCCTRecLocal;	
#endif

    

    /**/pdebug(("--idle_exit--"));/**/

    /* Clean out card buff              */
    vdFlushCardBuffer();

    /* Clean out CheckReader stuff      */
    //NKJT Check Reader
#ifdef CHECK_DEFINED
    inResult = inCloseCheckReader();
    /*  load CCT record in to local structure   */
    if (inLoadConfRec(CCT_FILE_NAME, SIZE_CCT_REC, 0, (char *) &srCCTRecLocal) == VS_SUCCESS) {
        //NKJT Check Reader
        inResult = inInitCheckReader(VS_FALSE, &srCCTRecLocal);
    }
    /* Clear any triggered traps */
    srGDS.fCheckSwipeFromIdle = VS_FALSE;
#endif



#ifdef PP501_ICPA
    inResetPINPad501();
#endif

    /* Update display */
    fDisplayLogoNow = VS_TRUE;

    // Reset Password Security Level
    vdSetPWSecurityLevel(ACCESS_FREELY);

    /* Clean out keyboard buff          */
    vdFlushKeyboardBuffer();
    pdebug(("MAX Heap used = %ld.", _heap_max()));

#ifdef MOBITEX_DEFINED
    // We must have done dialbackup, landline if docked or Amex PIP
    // so let's get the radio modem set up again so we can get RSSI @ idle
    if (srGDS.fWirelessActive && obCommunication.inLinkType != MOBITEX_COMM) {
        inResult = inGetRadioCommHost();

        if (inResult != VS_ERR) {
            // Can't use inLoadDefaultHost() because it tries to load
            // pobTran which doesn't exist because we are called after
            // inOperations() and inOperations() released pobTran.

            // All we need to do here is load a valid wireless host HDT
            // so we can initialize Mobitex comm which uses HDT's comm idx
            // to run inBeginMobitexComm().
            if (inLoadHostData(inResult) == VS_SUCCESS) {
                // inInitializeComm() needs pobTran too so use this

                if (obCommunication.inLinkType != shGetCommLinkType()) {
                    /* check if there's no comm object before trying to Deinitialize it */
                    if (obCommunication.inLinkType != NO_COMM) {
                        if (obCommunication.inDeinitialize)
                            obCommunication.inDeinitialize(&obCommunication);
                    }
                } /* end if link types don't match */

                if (shGetCommLinkType() == MOBITEX_COMM) {
                    vdInitializeMobitexComm(&obCommunication);
                    obCommunication.inInitialize(&obCommunication);
                }
            } /* end if load host success */
        } /* end if wireless host exists */
    } /* end if wireless active and not Mobitex */
#endif

    if (srGDS.fResetIdleTimer) {  //This is commented by LeeChyi, and uncommented by liem. 
        srGDS.ulIdleTimerCount = set_itimeout(NO_CLOCK_HANDLE inGetIdleTimeOut(), TM_SECONDS);
		srGDS.ulIdleTimerCount = srGDS.ulIdleTimerCount + (lnBackLightTimer-120000L);  //
		LOG_PRINTFF((0x08L, "IDLE EXIT: Timer Reset"));
	}
    srGDS.fResetIdleTimer = VS_TRUE;

//	inImamDownloadBlankLogo();
//	inImamOpenComDevice();

	disable_hot_key();  //liem to disable hot key
	LOG_PRINTFF((0x08L, "IDLE EXIT: Redraw Menu"));
	vdImamDisplayMenu(4);

    return(BRANCH_EXIT);                /* less than zero signals error    */
}

int inNoKeyPoll(int state) {
    /** /pdebug(("--inNoKeyPoll--"));*/
    return(BRANCH_EXIT);
}

/*-------------------------------------------------------------------------
    Function    : vdDisableClearKey ()
    Description :
    Parameters  :

    Returns     :
    Globals     :
    Notes       :

    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   02/05/98 Kevin_v1   Function created.
--------------------------------------------------------------------------*/

/*******************************************************************
*    Function Name:  trap_clr_key_disabled ()
*
*    Description:    Sound ERROR Tone when clear key is pressed.
********************************************************************/

void trap_clr_key_disabled(int trap_num) {
    ERR_BEEP();
}


//****** BRG 10/06/99
void vdDisableClearKey(int inAction) {
}
//****** BRG 10/06/99 END

/*******************************************************************
*    Function Name:  trap_ckrdr_disabled ()
*
*    Description:    ...
********************************************************************/

void trap_ckrdr_disabled(int trap_num) {
}


//****** BRG 10/06/99
void vdDisableCheckReader(int inAction) {
}
//****** BRG 10/06/99 END



//****** BRG 10/06/99
void vdClearKeyGuardSlot(int inAction) {
}
//****** BRG 10/06/99 END

/*******************************************************************
*    Function Name:  trap_clr_key ()
*
*    Description:    Turn on "abort flag" when clear key is pressed.
********************************************************************/

void trap_clr_key(int trap_num) {
    /** /pdebug (("--trap_clr_key--"));*/
    //    gu_clr_state = 1;
}

/*******************************************************************
*    Function Name:  fast_poll(), slow_poll()
*
*    Description:    These two functions provide hooks int the two
*                    loops within the Application Idle Engine (AIE)
*                    fast_poll() is the hook into the 50ms loop
*                    slow_poll() is the hook into the 250ms loop
*
*    Programmer      Jim_B4
********************************************************************/

short slow_poll() {
    /** /pdebug (("--slow_poll--"));*/
    return(BRANCH_EXIT);
}

short fast_poll() {
    /** /pdebug (("--fast_poll--"));*/
    return(BRANCH_EXIT);
}



/*******************************************************************
*    Function Name:  inDoEESLEvent()
*
*    Description:  MAM Addition. Processes PIPE events during IDLE. If a pipe
*                   event is received, check for a CUSTOM EVENT.
*    Programmer
********************************************************************/
int inDoEESLEvent()
{
	   //jrd one source
    #ifdef __arm
    unsigned short ushEventDataSize = 0;
    #endif
    #ifdef _TARG_68000
     unsigned int ushEventDataSize = 0;
    #endif
	
	unsigned short ushEESLAPIReturnValue = 0;

	char szLogicalName[16];
	unsigned char szEventDataBuffer[512];

	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Inside inDOEESLEvent()"));

	if (EESL_queue_count() == 0)
		return BRANCH_EXIT ;

	while (EESL_queue_count() != 0)
	{
		ushEESLAPIReturnValue = EESL_read_cust_evt(	szEventDataBuffer, sizeof(szEventDataBuffer),
												&ushEventDataSize, szLogicalName);

		LOG_PRINTFF((EESL_DEBUG_GLOBAL, "EESL_read_cust_evt() %u %s %u %s",
						ushEESLAPIReturnValue, szEventDataBuffer, ushEventDataSize, szLogicalName));
	}

	return ushEESLAPIReturnValue;
}



/*******************************************************************
*    Function Name:  inDoActivate()
*
*    Description:  MAM Addition.A Custom activate event was received.
*                   from DEVMAN.
*    Programmer
********************************************************************/
int inDoActivate()
{
	int inRetVal;		//meca 20041023 -- fixed from cashcard O3750 -- for auto-processing in multi-app environment 
	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "ACT_EVENT received"));

	vdPrintDebugLog();

	hConsoleS = open(DEV_CONSOLE, 0);
	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Opening the console : %d", hConsoleS));

	vdPrintDebugLog();

	//ATS Bug Fix 35
	lnAppActivateEvent = 999L;

	inImamInitUclCommEx();  //


    //meca 20041023 -- fixed from cashcard O3750 -- for auto-processing in multi-app environment --start
	// alvin_m1 -To ensure that resources are acquired only when EVENT is from Event Manager (?-assumption)
	F2_F4_Flag = VS_TRUE;			// This is to fix the F2-F4 wrong password
	// end alvin_m1

	//return (inAppl_activate());
	inRetVal = inAppl_activate();
	srGDS.fSoftPayActive = VS_TRUE;

	return (inRetVal);
    //meca 20041023 -- fixed from cashcard O3750 -- for auto-processing in multi-app environment --end
	
}


/*******************************************************************
*    Function Name:  inDoActivate()
*
*    Description:  MAM Addition.A Custom activate event was received.
*                   from DEVMAN.
*    Programmer
********************************************************************/
int inDoDeActivate()
{
	long	lnEESLAPIReturnValue = 0;
	unsigned short ushEvent = 0;

	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Deactivate request received"));

	if (inMAMAvailable)
	{
		// alvin_m1 - To ensure Softpay MAIN MENU is shown when SOFTPAY is selected //from VMAC Menu
		vdSelectMenu(ROOT_MENU_ID);

		inImamReleaseComm(); //

		inAppl_deactivate();

		vdPrintDebugLog();

		close(hConsoleS) ;
		SVC_WAIT(500);
		LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Closing the console %d", hConsoleS));

		vdPrintDebugLog();

		ushEvent = ACT_EVENT;
		LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Releasing devices"));

		lnEESLAPIReturnValue = EESL_send_event("DEVMAN", RES_COMPLETE_EVENT, (unsigned char*)&ushEvent, sizeof(ushEvent));
		while (lnEESLAPIReturnValue != 0)
		{
			SVC_WAIT(200);
			lnEESLAPIReturnValue = EESL_send_event("DEVMAN", RES_COMPLETE_EVENT, (unsigned char*)&ushEvent, sizeof(ushEvent));
		}
	}

//meca 20041023 -- fixed from cashcard O3750 -- for auto-processing in multi-app environment (bruce/sadiq)
	srGDS.fSoftPayActive = VS_FALSE;		// Mark SoftPay as inActive
//meca 20041023 -- fixed from cashcard O3750 -- for auto-processing in multi-app environment (bruce/sadiq)

	SVC_WAIT(100);
	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "De-Activate Complete"));

	return (BRANCH_EXIT);
}


/*******************************************************************
*    Function Name:  inDoMAMOperate()
*
*    Description:  Invokes functionality defined in the operation table.
*                   The event that starts the transation is a custom event
*                   received via MAM.
*    Programmer
********************************************************************/
int inDoMAMOperate() {
    //  unsigned char pucMAMEventData[255];
    //  unsigned int inMAMEventDataSize;
    //  char pchSenderLogicalName[20];
    short inError = 0;
    short shOperationCode;
    short shSubOperationCode;
    long lnTranMsg;

	vdPrintDebugLog();

	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Custom select event received"));

	hConsoleS = open(DEV_CONSOLE, 0);
	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Opening the console : %d", hConsoleS));

	vdPrintDebugLog();

    /* Activate Softpay */
    if (fGetEnablePrinter()) {
        //pdebug (("PCTEnablePrinter"));
        if (obPrinter.inHandle <= 0) {
            //pdebug (("inOpenPrinter"));
            inOpenPrinter();
            inSelectTemplateFile(&obPrinter);
            p350LinesPerInch(inGetP350LinesPerInch());
            p350ColumnMode(inGetP350ColMode());
        }
    }

    if (hCardReader <= 0)
        hCardReader = open(DEV_CARD, O_RDWR);

    /* Activation complete - cannot call the activate routine, because it refreshes the screen */
    //inAppl_activate();

    LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Activate complete"));
    /* Initialise the stadard variable record */
    if (usMAMEventDataSize != 0)
        inError = ushInitStandardFlexi(pucMAMEventData);
    else {
        inError = 1;
        LOG_PRINTFF((EESL_DEBUG_GLOBAL, "NO CUSTOM EVENT DATA"));
    }

    if (!inError) {

//jrd one source
    #ifdef __arm
    /* Get a typed field from a variable record */
        inError = shVarGetUnsignedInt(MAM_OPERATION_CODE, (unsigned short *) &shOperationCode);

        /* Get a typed field from a variable record */
        inError += shVarGetUnsignedInt(MAM_SUB_OPERATION_CODE, (unsigned short *) &shSubOperationCode);
       
    #endif
    #ifdef _TARG_68000
     /* Get a typed field from a variable record */
        inError = shVarGetUnsignedInt(MAM_OPERATION_CODE, (unsigned int *) &shOperationCode);

        /* Get a typed field from a variable record */
        inError += shVarGetUnsignedInt(MAM_SUB_OPERATION_CODE, (unsigned int *) &shSubOperationCode);

    #endif
	 /* Get a typed field from a variable record */
        inError += shVarGetUnsignedLong(MAM_TRAN_MSG_CODE, (unsigned long *) &lnTranMsg);
        
    } else
        LOG_PRINTFF((EESL_DEBUG_GLOBAL, "EVENT DATA IS NOT A FLEXI REC!"));


    /* Call the operation */
    if (!inError) {
        LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Call OP %d: SUBOP: %d MSG %ld", shOperationCode, shSubOperationCode, lnTranMsg));
        disable_hot_key();
        clrscr();
        vdSetActionFont();
        vdDisplayTranTitle(lnTranMsg);
        /* Call the required operation */
        inOperations(shOperationCode, shSubOperationCode, lnTranMsg);
        vdSetMenuFont();
        vdSelectMenu(ROOT_MENU_ID);
        enable_hot_key();
    } else
        LOG_PRINTFF((EESL_DEBUG_GLOBAL, "INVALID FLEXI RECORD!"));

    return (BRANCH_EXIT);
}




/*******************************************************************
*    Function Name:  inDoActivate()
*
*    Description:  MAM Addition.A Custom activate event was received.
*                   from DEVMAN.
*    Programmer
********************************************************************/
int inDoTMAOperate() {

#ifdef TMA_DEFINED	
   short shlength;
   unsigned short usLength;
   unsigned char  dataBuf[100];
#endif
   int ushEvent = 0;
    int error = 0;
    
    short shMeid = 0;
    char chInstance = 0;
    long offset = 0;
    int inTmaError = 0;
   

#ifdef TMA_DEFINED


    LOG_PRINTF(("TMA REQUEST"));
    /* Find the length of the flexi field */
    error = shGetRecordLength(pucMAMEventData, &shlength);

    if (!error) {
        LOG_PRINTF(("REQUEST FOR APP MEID. Data length:%d", shlength));

        error = shVarGetField((pucMAMEventData), MIID, (unsigned char *) &shMeid, sizeof(shMeid), &shlength);  // Get MEID field from flexirecord
        shVarGetField((pucMAMEventData), MIID_INSTANCE, (unsigned char *) &chInstance, sizeof(chInstance), &shlength); // Get MEID_INSTANCE field from flexirecord
        LOG_PRINTF(("REQUEST FOR TMAIL MEID %d , INSTANCE:%d er: %d", shMeid, chInstance, error));


        /* Call the associated TMA function pointer */
        inTmaError = inRunMEIDFunction((int) shMeid, (int) chInstance, dataBuf, &usLength);

        //pdebug (("data %s",dataBuf));
        pdebug(("length %d", usLength));
        LOG_PRINTF(("Response :error:%d", inTmaError));



        /* Populate the outgoing event data with the TMA flexi record */
        vVarInitRecord(pucMAMEventData, sizeof(pucMAMEventData), 0); // Create a flexi record
        shVarAddField(pucMAMEventData, MIID_VALUE, dataBuf, usLength);  // Set the value of the MEID_VALUE
        shVarAddField(pucMAMEventData, MIID_ERROR, (unsigned char *) &inTmaError, 1); // Set the value of the MEID_ERROR to "0" if no error
        shGetRecordLength(pucMAMEventData, &shlength);
        //Send event to TMA
        error = EESL_send_event("TMA", TM_GET_RESPONSE, pucMAMEventData, length);
        SVC_WAIT(0);
        LOG_PRINTF(("RESPONSE SENT FROM APPLICATION"));
        LOG_PRINTF(("EESL_Send return Value:%d", error));
        if (error != 0) {
            SVC_WAIT(100);
            error = EESL_send_event("TMA", TM_GET_RESPONSE, pucMAMEventData, length);
            SVC_WAIT(0);
            LOG_PRINTF(("RESPONSE SENT FROM APPLICATION"));
            LOG_PRINTF(("EESL_Send return Value:%d", error));
        }
    }//if error

#endif
    return (BRANCH_EXIT);
}



/*******************************************************************
*    Function Name:  inDoSPOperation()
*
*    Description:  MAM Addition.A Custom activate event was received.
*                   from DEVMAN.
*    Programmer
********************************************************************/
int inDoSPOperation() {
    int error = 0,
    retval = 0;

//jrd one source
    #ifdef __arm
    unsigned short length;
    #endif
    #ifdef _TARG_68000
     unsigned int length;
    #endif
    
    
   // unsigned short iEvent;
    int inOperationCode;
    int inSubOperationCode = 0;
    long lnTranMsg;
    char szSenderLogicalName[15];

	int inEESLAPIReturnValue;
	unsigned short ushEvent;

    LOG_PRINTF(("External Request For SP Operation"));

    retval = shVarGetField((pucMAMEventData), EXTERN_APP_NAME, (unsigned char *) szSenderLogicalName, sizeof(szSenderLogicalName), &length);
    LOG_PRINTF(("Trying to get extern app name. Name:%s", szSenderLogicalName));

    /* Find the length of the flexi field */

	//jrd one source
    #ifdef __arm
    error = shGetRecordLength(pucMAMEventData, (short *) &length);
    #endif
    #ifdef _TARG_68000
    error = shGetRecordLength(pucMAMEventData, (int *) &length);
    #endif

    

    LOG_PRINTF(("REQUEST FOR SP Operation. Data length:%d", length));

    if (!error) {
        // We have a valid flexi record, go ahead and open the devices.

        srGDS.fExternalEvent = VS_TRUE;

		vdPrintDebugLog();

		hConsoleS = open(DEV_CONSOLE, 0);
		LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Opening the console : %d", hConsoleS));

		vdPrintDebugLog();

        /* Activate Softpay */
        if (fGetEnablePrinter()) {
            //pdebug (("PCTEnablePrinter"));
            if (obPrinter.inHandle <= 0) {
                //pdebug (("inOpenPrinter"));
                inOpenPrinter();
                inSelectTemplateFile(&obPrinter);
                p350LinesPerInch(inGetP350LinesPerInch());
                p350ColumnMode(inGetP350ColMode());
            }
        }

        if (hCardReader <= 0)
            hCardReader = open(DEV_CARD, O_RDWR);

#ifdef ICC_DEFINED
        Init_CardSlot(CUSTOMER_CARD);
#endif

        // Read the field data from the flexi record
        // Populate fields which have been provided, these fields do not have to be prompted for.

        error = shVarGetField((pucMAMEventData), OPERATION_ID, (unsigned char *) &inOperationCode, sizeof(inOperationCode), &length);  // Get MEID field from flexirecord

        error += shVarGetField((pucMAMEventData), TRANSACTION_ID, (unsigned char *) &inSubOperationCode, sizeof(inSubOperationCode), &length); // Get MEID_INSTANCE field from flexirecord

        inGetTransMsgID(inOperationCode, inSubOperationCode, &lnTranMsg);

        /* Run the operation / transacation */

        if (!error) {
            LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Call OP %d: SUBOP: %d MSG %ld", inOperationCode, inSubOperationCode, lnTranMsg));
            disable_hot_key();
            clrscr();
            vdSetActionFont();
            vdDisplayTranTitle(lnTranMsg);
            /*  Call the required operation */
            inOperations(inOperationCode, inSubOperationCode, lnTranMsg);
            vdSetMenuFont();
            vdSelectMenu(ROOT_MENU_ID);
            enable_hot_key();
            LOG_PRINTF(("Completed softpay tran"));
        } else
            LOG_PRINTFF((EESL_DEBUG_GLOBAL, "INVALID FLEXI RECORD!"));

//jrd one source
    #ifdef __arm
    error = shGetRecordLength(pucMAMEventData, (short *) &length); //Getting length of the outgoing flexi record.
    #endif
    #ifdef _TARG_68000
       error = shGetRecordLength(pucMAMEventData, (int *) &length); //Getting length of the outgoing flexi record.
    #endif
      
        LOG_PRINTF(("Length of outgoing flexi : %d and error = %d", length, error));


        // close all devices
        inAppl_deactivate();

        /* Close the console */

	vdPrintDebugLog();

	close(hConsoleS) ;
	SVC_WAIT(500);
	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Closing the console %d", hConsoleS));

	vdPrintDebugLog();

        // Send RES_COMPLETE Event to Devman

	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Sending RES_COMPLETE_EVENT"));
	ushEvent = SP_OPERATION_IN;

	inEESLAPIReturnValue = EESL_send_event("DEVMAN", RES_COMPLETE_EVENT, (unsigned char*)&ushEvent, sizeof(ushEvent));
	while (inEESLAPIReturnValue != 0)
	{
		SVC_WAIT(200);
		inEESLAPIReturnValue = EESL_send_event("DEVMAN", RES_COMPLETE_EVENT, (unsigned char*)&ushEvent, sizeof(ushEvent));
	}

	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Sending SP_OPERATION_COMPLETE"));

	inEESLAPIReturnValue = EESL_send_event("DEVMAN", SP_OPERATION_COMPLETE, pucMAMEventData, length);
	while (inEESLAPIReturnValue != 0)
	{
		SVC_WAIT(200);
		inEESLAPIReturnValue = EESL_send_event("DEVMAN", SP_OPERATION_COMPLETE, pucMAMEventData, length);
	}

        SVC_WAIT(0);
    }

    srGDS.fExternalEvent = VS_FALSE;

    return (BRANCH_EXIT);
}


int inGetTransMsgID(int inOperationCode,int inSubOperationCode,long* plnTranMsg) {
    char szMenusFileName[FILENAME_SIZE + 1]; // Buffer for Menu File name
    char stVerInfo[GEN_VER_SIZE];
    int inMenuFile;                      // Handle for Menu file
    MenuItem srMenu;
    int inResult = 0;

    PFI_PSZ_INT pinTempFn;

    /** /pdebug(("--vdGetTransMsgID--"));*/
    /*
     *      Load Menus File Name
     */

    if ((pinTempFn = inGetFunctionPointer(GET_MENU_FILE_NAME)) == NULL_PFI)
        return(VS_ERR);

    if (pinTempFn(szMenusFileName, sizeof(szMenusFileName)) != VS_SUCCESS)
        return(VS_ERR);

    if ((inMenuFile = open(szMenusFileName, O_RDONLY)) != -1) {
        if (read(inMenuFile, stVerInfo, GEN_VER_SIZE) != GEN_VER_SIZE) {
            close(inMenuFile);
            /** /pdebug(("Bad read ver fld"));*/
            return(VS_ERR);
        }

        memset(&srMenu, 0, sizeof(srMenu));
        inResult = read(inMenuFile, (char *) &srMenu, sizeof(srMenu));

        while (inResult > 0) {
            if ((srMenu.miFuncIndex == inOperationCode) && (srMenu.miSubFuncIndex == inSubOperationCode))
                break;

            inResult = read(inMenuFile, (char *) &srMenu, sizeof(srMenu));
        }
        *plnTranMsg = srMenu.mlTranMsg;

        /*
         *      Close file if open
         */
        if (inMenuFile > 0) {
            if ((inResult = close(inMenuFile)) < 0)
                return (VS_ERR);
        }
    }
    return (VS_SUCCESS);
}

void vdLoadExternalEventData(TRANSACTION_OBJECT* pobTran) {
    int error = 0;

  //jrd one source
    #ifdef __arm
     unsigned short length;
    #endif
    #ifdef _TARG_68000
     unsigned int length;
    #endif
    
    // Read the field data from the flexi record
    // Populate fields which have been provided, these fields do not have to be prompted for.

    error = shVarGetField((pucMAMEventData), CARD_ACCT_NUMBER_IN, (unsigned char *) pobTran->srBRec.szPAN, PAN_SIZE + 1, &length);  // Get Card Number field from flexirecord

    error += shVarGetField((pucMAMEventData), CARD_EXPIRE_DATE_IN, (unsigned char *) pobTran->srBRec.szExpDate, EXP_DATE_SIZE + 1, &length); // Get Expiry Date field from flexirecord

    error += shVarGetField((pucMAMEventData), CARD_USER_NAME, (unsigned char *) pobTran->srBRec.szCHolder, CHOLDER_SIZE + 1, &length); // Get Card Holder Name field from flexirecord

    error += shVarGetField((pucMAMEventData), BASE_AMOUNT_IN, (unsigned char *) &(pobTran->srBRec.lnBaseTransactionAmount), sizeof(long), &length);

    error += shVarGetField((pucMAMEventData), TAX_AMOUNT, (unsigned char *) pobTran->srBRec.lnTaxAmount, sizeof(long), &length);

    error += shVarGetField((pucMAMEventData), TIP_AMOUNT, (unsigned char *) pobTran->srBRec.lnTipAmount, sizeof(long), &length);

    error += shVarGetField((pucMAMEventData), AVS_ZIP_CODE, (unsigned char *) pobTran->szZipCode, ZIPCODE_SIZE + 1, &length);

    error += shVarGetField((pucMAMEventData), AVS_ADDRESS_ID, (unsigned char *) pobTran->szAddress, ADDRESS_SIZE + 1, &length);

    error += shVarGetField((pucMAMEventData), CVV2_CVC2_VALUE, (unsigned char *) pobTran->szCVV2Value, CVV2_SIZE + 1, &length);

    error += shVarGetField((pucMAMEventData), CVV2_PRESENCE_IND, (unsigned char *) pobTran->chCVV2PresenceIndicator, sizeof(char), &length);

    error += shVarGetField((pucMAMEventData), RECEIPT_MSG1, (unsigned char *) srRcpt.szMultiAppMsg1, RECEIPT_HEADER_SIZE + 1, &length);

    error += shVarGetField((pucMAMEventData), RECEIPT_MSG2, (unsigned char *) srRcpt.szMultiAppMsg2, RECEIPT_HEADER_SIZE + 1, &length);

    LOG_PRINTF(("Receipt Message1 is %s", srRcpt.szMultiAppMsg1));
    LOG_PRINTF(("Receipt Message2 is %s", srRcpt.szMultiAppMsg2));

    /*
    ENTRY_INDICATOR

    CLERK_ID

    RECEIPT_MSG1

    RECEIPT_MSG2

    ICC_DATA

    pending IDs to be mapped.
    */
}

void vdLoadExternalRespData(TRANSACTION_OBJECT* pobTran,int inResult) {
    LOG_PRINTF(("Inside load response"));

    LOG_PRINTF(("Receipt Message1 is %s", srRcpt.szMultiAppMsg1));
    LOG_PRINTF(("Receipt Message2 is %s", srRcpt.szMultiAppMsg2));


    vVarInitRecord(pucMAMEventData, 450, 0); // Create a flexi record

    LOG_PRINTF(("inResult = %d", inResult));

    if (inResult == VS_ESCAPE)
        shVarAddField(pucMAMEventData, USER_CANCELED, (unsigned char *) &inResult, sizeof(int));
    else {
        shVarAddField(pucMAMEventData, CARD_ACCT_NUMBER_OUT, (unsigned char *) pobTran->srBRec.szPAN, PAN_SIZE + 1);

        shVarAddField(pucMAMEventData, CARD_EXPIRE_DATE_OUT, (unsigned char *) pobTran->srBRec.szExpDate, EXP_DATE_SIZE + 1);

        shVarAddField(pucMAMEventData, TOTAL_AMOUNT, (unsigned char *) &(pobTran->srBKey.lnTotalOfTransactionAmount), sizeof(long));

        if (pobTran->srBRec.inTransactionResult == AUTHORIZED)
            shVarAddField(pucMAMEventData, APPROVAL_CODE, (unsigned char *) pobTran->srBRec.szAuthCode, AUTH_CODE_SIZE + 1);

        if (pobTran->srBRec.inTransactionResult == DECLINED)
            shVarAddField(pucMAMEventData, DECLINE_CODE, (unsigned char *) pobTran->srBRec.szAuthCode, AUTH_CODE_SIZE + 1);

        shVarAddField(pucMAMEventData, TRAN_CARD_TYPE, (unsigned char *) &(pobTran->srBRec.inTranCardType), sizeof(int));

        shVarAddField(pucMAMEventData, TRANSACTION_DATE, (unsigned char *) pobTran->srBRec.szDate, DATE_SIZE + 1);

        shVarAddField(pucMAMEventData, TRANSACTION_TIME, (unsigned char *) pobTran->srBRec.szTime, TIME_SIZE + 1);

        shVarAddField(pucMAMEventData, INVOICE_NUMBER, (unsigned char *) &(pobTran->srBKey.lnInvNum), sizeof(long));
    }

    LOG_PRINTF(("Completed Load response"));
}



/*******************************************************************
*    Function Name:  inCallNewMessageEvent(), etc.
*
*    Description:  Calls the specific functions to process the MAM
*                   events.
*    Programmer:   Michele Maitland
********************************************************************/
int inCallNewMessageEvent() {
#ifdef MESSENGER_DEFINED
    inDoNewMessageEvent(pucMAMEventData, usMAMEventDataSize);
#endif

    return (BRANCH_EXIT);
} /* end func inCallNewMessageEvent() */

int inCallNewGraphicEvent() {
#ifdef MESSENGER_DEFINED
    inDoNewGraphicEvent(pucMAMEventData, usMAMEventDataSize);
#endif

    return (BRANCH_EXIT);
} /* end func inCallNewGraphicEvent() */

int inCallNewVoucherEvent() {
#ifdef MESSENGER_DEFINED
    inDoNewVoucherEvent(pucMAMEventData, usMAMEventDataSize);
#endif

    return (BRANCH_EXIT);
} /* end func inCallNewVoucherEvent() */

int inCallNewReportEvent() {
#ifdef MESSENGER_DEFINED
    inDoNewReportEvent(pucMAMEventData, usMAMEventDataSize);
#endif

    return (BRANCH_EXIT);
} /* end func inCallNewReportEvent() */


/*******************************************************************
*    Function Name:  inDoVMACCardSelect(), etc.
*
*    Description:  Handles a mag card initiated selection event from SELECT.
*    Programmer:   Bruce Girdlestone
********************************************************************/
int inDoVMACCardSelect() {
    /* Treat this as an activate event */
    LOG_PRINTF(("In the SELECT routine"));
    inDoActivate();
    inVMACCardSelect = 1;
    LOG_PRINTF(("Data size %d", usMAMEventDataSize));
    pucMAMEventData[10] = 0;
    LOG_PRINTF(("First 10 bytes : %s", pucMAMEventData));

    /* Call the card selection function */
	inCardResponder();

    /* Deactivate */
    inDoDeActivate();

    return (BRANCH_EXIT);
} /* end func inDoVMACCardSelect() */

int inGetVMACSelectCArdData(char* pucCardData) {
    if (inVMACCardSelect) {
        inVMACCardSelect = 0;
        memcpy(pucCardData, pucMAMEventData, usMAMEventDataSize);
        return 250;
    }
    return 0;
}/* end func inGetVMACSelectCArdData() */


int inCheckVMACCardSelect() {
    return inVMACCardSelect;
}/* end func inGetVMACSelectCArdData() */






/**************************************************************************/
/*                    Idle transaction Process table                      */
/**************************************************************************/
PF_TABLE appl_table[] = {
    #define FT_EXIT                             0
    (PF_TABLE) idle_exit,
    #define NO_KEY                              1
    (PF_TABLE) inNoKeyPoll,
    #define    FT_EVENT_AKEY                    2
    (PF_TABLE) inAKeyResponder,
    #define    FT_EVENT_BKEY                    3
    (PF_TABLE) inBKeyResponder,
    #define    FT_EVENT_CKEY                    4
    (PF_TABLE) inCKeyResponder,
    #define    FT_EVENT_DKEY                    5
    (PF_TABLE) inDKeyResponder,
    #define    FT_EVENT_F0KEY                   6
    (PF_TABLE) inImamF0KeyResponder,
    #define    FT_EVENT_EKEY                    7
    (PF_TABLE) inEKeyResponder,
    #define    FT_EVENT_FKEY                    8
    (PF_TABLE) inFKeyResponder,
    #define    FT_EVENT_GKEY                    9
    (PF_TABLE) inGKeyResponder,
    #define    FT_EVENT_HKEY                    10
    (PF_TABLE) inHKeyResponder,
    #define    FT_EVENT_F5KEY                   11
    (PF_TABLE) inImamF5KeyResponder,
    #define    FT_EVENT_0KEY                    12
    (PF_TABLE) in0KeyResponder,
    #define    FT_EVENT_1KEY                    13
    (PF_TABLE) in1KeyResponder,
    #define    FT_EVENT_2KEY                    14
    (PF_TABLE) in2KeyResponder,
    #define    FT_EVENT_3KEY                    15
    (PF_TABLE) in3KeyResponder,
    #define    FT_EVENT_4KEY                    16
    (PF_TABLE) in4KeyResponder,
    #define    FT_EVENT_5KEY                    17
    (PF_TABLE) in5KeyResponder,
    #define    FT_EVENT_6KEY                    18
    (PF_TABLE) in6KeyResponder,
    #define    FT_EVENT_7KEY                    19
    (PF_TABLE) in7KeyResponder,
    #define    FT_EVENT_8KEY                    20
    (PF_TABLE) in8KeyResponder,
    #define    FT_EVENT_9KEY                    21
    (PF_TABLE) in9KeyResponder,
    #define    FT_EVENT_STAR_KEY                22
    (PF_TABLE) inStarKeyResponder,
    #define    FT_EVENT_POUND_KEY               23
    (PF_TABLE) inPoundKeyResponder,
    #define    FT_EVENT_CANCEL_KEY              24
    (PF_TABLE) inCancelKeyResponder,
    #define    FT_EVENT_BS_KEY                  25
    (PF_TABLE) inBackSpaceKeyResponder,
    #define    FT_EVENT_ALPHA_KEY               26
    (PF_TABLE) inAlphaKeyResponder,
    #define    FT_EVENT_ENTER_KEY               27
    (PF_TABLE) inImamEnterKeyResponder,
    #define    FT_EVENT_CARD                    28
    (PF_TABLE) inCardResponder,
    #define    FT_EVENT_MDMIN                   29
    (PF_TABLE) inModemInResponder,
    #define    FT_EVENT_PININ                   30
    (PF_TABLE) inPinInResponder,
    #define    FT_EVENT_C1_IN                   31
    (PF_TABLE) inC1_InResponder,
    #define    FT_EVENT_C2_IN                   32
    (PF_TABLE) inC2_InResponder,
    #define    FT_EVENT_C3_IN                   33
    (PF_TABLE) inC3_InResponder,
    #define    FT_EVENT_ACTIVATE                34
    (PF_TABLE) inAppl_activate,
    #define    FT_EVENT_DEACTIVATE              35
    (PF_TABLE) inAppl_deactivate,

    //MAM Addition
    #define FT_CUSTOME                          36
    (PF_TABLE) inDoEESLEvent,
    #define PF_ACTIVATE                     37
    (PF_TABLE) inDoActivate,
    #define PF_DEACTIVATE                       38
    (PF_TABLE) inDoDeActivate,
    #define PF_MAM_OPERATE                      39
    (PF_TABLE) inDoMAMOperate,


     #define PF_ICICI_CUST_DEACTIVATE		40
     (PF_TABLE)inICICICustomDeActivate,

    #ifdef TMA_DEFINED
    #define PF_GET_REQUEST                      41
    (PF_TABLE) inDoTMAOperate,
    #endif

    //Messenger (Tmail) Addition
    #define FT_MESSAGE                          41
    (PF_TABLE) inCallNewMessageEvent,
    #define FT_GRAPHIC                          42
    (PF_TABLE) inCallNewGraphicEvent,
    #define FT_VOUCHER                          43
    (PF_TABLE) inCallNewVoucherEvent,
    #define FT_REPORT                           44
    (PF_TABLE) inCallNewReportEvent,
    #define FT_EVENT_CARD_SELECT                45
    (PF_TABLE) inDoVMACCardSelect,
    #define PF_GET_EXTERN_REQUEST               46
    (PF_TABLE) inDoSPOperation,
    #ifdef ICC_DEFINED

    #define    FT_EVENT_ICC1CARD                47
    (PF_TABLE) inICC1Responder,
    #define    FT_EVENT_ICC2CARD                48
    (PF_TABLE) inICC2Responder,
    #endif

    (PF_TABLE) END_TABLE
};

/**************************************************************************/
/*                    Main Idle State Branch Table                        */
/*            (this table is required for every application)              */
/**************************************************************************/
BRANCH_TBL_ENTRY idle_table[] = {
    { EXIT_FUNC,        FT_EXIT,                  idle_table    },
    { KEY_a,            FT_EVENT_AKEY,            idle_table    },
    { KEY_b,            FT_EVENT_BKEY,            idle_table    },
    { KEY_c,            FT_EVENT_CKEY,            idle_table    },
    { KEY_d,            FT_EVENT_DKEY,            idle_table    },
#ifdef KEY_F0
    { KEY_F0,           FT_EVENT_F0KEY,           idle_table    },
#endif
    { KEY_e,            FT_EVENT_EKEY,            idle_table    },
    { KEY_f,            FT_EVENT_FKEY,            idle_table    },
    { KEY_g,            FT_EVENT_GKEY,            idle_table    },
    { KEY_h,            FT_EVENT_HKEY,            idle_table    },
#ifdef KEY_F5
    { KEY_F5,           FT_EVENT_F5KEY,           idle_table    },  
#endif
    { KEY0,             FT_EVENT_0KEY,            idle_table    },
    { KEY1,             FT_EVENT_1KEY,            idle_table    },
    { KEY2,             FT_EVENT_2KEY,            idle_table    },
    { KEY3,             FT_EVENT_3KEY,            idle_table    },
    { KEY4,             FT_EVENT_4KEY,            idle_table    },
    { KEY5,             FT_EVENT_5KEY,            idle_table    },
    { KEY6,             FT_EVENT_6KEY,            idle_table    },
    { KEY7,             FT_EVENT_7KEY,            idle_table    },
    { KEY8,             FT_EVENT_8KEY,            idle_table    },
    { KEY9,             FT_EVENT_9KEY,            idle_table    },
    { KEY_STR,          FT_EVENT_STAR_KEY,        idle_table    },
    { KEY_PND,          FT_EVENT_POUND_KEY,       idle_table    },
    { KEY_CANCEL,       FT_EVENT_CANCEL_KEY,      idle_table    }, // BJD: KEY_CLR -> KEY_CANCEL
    { KEY_BS,           FT_EVENT_BS_KEY,          idle_table    },
    { KEY_ALP,          FT_EVENT_ALPHA_KEY,       idle_table    },
    { KEY_CR,           FT_EVENT_ENTER_KEY,       idle_table    },
    { APPL_CARD,        FT_EVENT_CARD,            idle_table    },
    { MDMIN,            FT_EVENT_MDMIN,           idle_table    },
    { PININ,            FT_EVENT_PININ,           idle_table    },
    { C1_IN,            FT_EVENT_C1_IN,           idle_table    },
    { C2_IN,            FT_EVENT_C2_IN,           idle_table    },
    { C3_IN,            FT_EVENT_C3_IN,           idle_table    },
    // MAM ADDITION - EVENTS
    { ACT_EVENT,        PF_ACTIVATE,                idle_table  },
    { PIPE_IN,          FT_CUSTOME,                 idle_table  },
    { DEACTIVATE_IN,    PF_DEACTIVATE,              idle_table  },
    { MAM_OPERATE_IN,   PF_MAM_OPERATE,             idle_table  },
    #ifdef TMA_DEFINED
    { TM_GET_REQUEST,   PF_GET_REQUEST,             idle_table  },
    #endif
    { SP_OPERATION_IN,  PF_GET_EXTERN_REQUEST,      idle_table  },

	//Change in ICICI appln to accomadate any other appln which has autosettlement in VMAC mode
	{ SP_ICICI_DEACTIVATE_EVENT,  PF_ICICI_CUST_DEACTIVATE,      idle_table  },


    // MESSENGER (Tmail) ADDITIONAL EVENTS
    { GRAL_MSG_AVAIL_EVENT,     FT_MESSAGE,         idle_table  },
    { GRAPH_MSG_AVAIL_EVENT,    FT_GRAPHIC,         idle_table  },
    { VOUCH_MSG_AVAIL_EVENT,    FT_VOUCHER,         idle_table  },
    { REPORT_MSG_AVAIL_EVENT,   FT_REPORT,          idle_table  },
    { SP_CARD_SELECT,   FT_EVENT_CARD_SELECT,          idle_table   },
    #ifdef ICC_DEFINED

    { ICC1_IN,          FT_EVENT_ICC1CARD,        idle_table    },
    { ICC2_IN,          FT_EVENT_ICC2CARD,        idle_table    },
    #endif

    // BELOW HANDLED BY LIBRARY
    //    { ACTIVATE_IN,      FT_EVENT_ACTIVATE,        idle_table    },
    //    { DEACTIVATE_IN,    FT_EVENT_DEACTIVATE,      idle_table    },

    /* ACTIVATES engine call to slow_poll()
    { SLOW_POLL_EVENT_1, SLOW_POLL_EVENT_1,   idle_table    },
    *********************************************************/

    { END_TABLE,    NO_KEY,                   idle_table    }
};


void vdInitMenus() {
    /*
     * Read in the menu description list.
     */
    long x;
    inFirstMenuKey = KEY_e;
    inLastMenuKey = KEY_h;
    //    inItemsPerPage   = 4;
    inScrollLeftKey = 0;     /* "^" up-arrow; swaps with "Right"   */
    inScrollRightKey = KEY_a; /* "V" down-arrow; swaps with "Left"  */

    //pmeCurrentMenu = &MenuList[ROOT_MENU_INDEX].meMenu;
    pmeCurrentMenu = 0;   // BJD

    vdSetMenuFont();
    /** /pdebug(("Make sure VC Opt is Off"));*/
    /** /pdebug(("Root Menu Value %d",ROOT_MENU_ID));*/
    x = lnAllocateMenu();

    vdSelectMenu(ROOT_MENU_ID);
}

/*-------------------------------------------------------------------------
    Function :      fUpdateMenus()
    Description :   Extracts SoftPay Assist Menus from Config.Sys and creates
                    menus???.dat.
    Parameters :    None
    Returns :       TRUE or FALSE indicating success or failure
    Globals :       None
    Notes :         None
    Modification History :
      #     Date      Who                     Description
    ----- -------- ---------- ---------------------------------------------
      0   01/14/98 Kevin_V1   Creation.
--------------------------------------------------------------------------*/

#define TEMP_FILE_NAME      "temp.tmp"

VS_BOOL fUpdateMenus(TRANSACTION_OBJECT* pobTran) {
    VS_BOOL fReturnValue = VS_TRUE,
    fUpdateMenus = VS_FALSE,
    fMenuHeader = VS_FALSE,
    fMoreVars;
    short inNumMenus = 0,
    inExpMenus = 0,
    inNumItems = 0,
    inExpItems = 0,
    inRecNum = 0,
    inFldSz = 0,
    inFldIdx = 0,
    inFldVal = 0,
    inResult = 0,
    inHandle = 0;
    char szMenusFileName[FILENAME_SIZE + 1],
    szLocBuf[1 + 1],
    szConfigName[MAX_CONFIG_NM_SIZE + 1],
    szConfigBuffer[MAX_ASSIST_CHUNK_SIZE + 1],
    szFmt[FILENAME_SIZE + 5],
    szTempBuffer[MAX_CONFIG_NM_SIZE + 1];
    MenuItem srMenu;

    PFI_PSZ_INT pinTempFn;

    /** /pdebug(("--fUpdateMenus--"));*/
    /*
     *      Load Menus File Name
     */
    if ((pinTempFn = inGetFunctionPointer(GET_MENU_FILE_NAME)) == NULL_PFI)
			return(VS_FALSE);

    if (pinTempFn(szMenusFileName, sizeof(szMenusFileName)) == VS_SUCCESS) {
        inRecNum = 1;
        fMoreVars = VS_TRUE;

        /*
         *     Search for all MENU records
         */
        while (fMoreVars) {
            if (inRecNum <= 99)
                strcpy(szFmt, "MENU%02d");
            else
                strcpy(szFmt, "MNU%03d");
            sprintf(szConfigName, szFmt, inRecNum);

            memset(szConfigBuffer, 0, sizeof(szConfigBuffer));
            if (get_env(szConfigName, szConfigBuffer, sizeof(szConfigBuffer)) <= 0)   /* No records */
                fMoreVars = VS_FALSE;
            else {
                fUpdateMenus = VS_TRUE;
                /*
                 *      Removed CONFIG.SYS parameter
                 */
                memset(szLocBuf, NULL_CH, sizeof(szLocBuf));
                put_env(szConfigName, szLocBuf, 0);

                /*
                 *      First Record Found, Open Menus file, and write header.
                 */
                if (inRecNum == 1) {
                    if (strlen(szConfigBuffer) == 16) {
                        if ((inHandle = open(TEMP_FILE_NAME, O_TRUNC | O_CREAT | O_RDWR)) < 0) {
                            extern int errno;
                            pdebug(("Open Failed=%s/%d/%d", "temp.tmp", inHandle, errno));
                            fReturnValue = VS_FALSE;
                            break;
                        }
                        if ((inResult = write(inHandle, szConfigBuffer, 16)) != 16) {
                            extern int errno;
                            pdebug(("Hdr Write Failed=%d/%d", inResult, errno));
                            fReturnValue = VS_FALSE;
                            break;
                        }
                    } else {
                        pdebug(("Hdr Failed=%s/%d", szConfigBuffer, strlen(szConfigBuffer)));
                        fReturnValue = VS_FALSE;
                        break;
                    }
                } else {
                    /*
                     *      Parse up to file fields of Menu Struct out of message data
                     */
                    inFldIdx = 1;
                    memset(&srMenu, 0, sizeof(srMenu));
                    while (inFldIdx <= 9) {
                        /*
                         *      Extract fields
                         */
                        if ((inFldSz = fieldvar(szConfigBuffer, inFldIdx, ':', szTempBuffer)) > 0) {
                            /*
                             *      convert to Int value
                             */
                            if (inFldIdx != 2)
                                inFldVal = atoi(szTempBuffer);
                            /*
                             *      store in Menu struct
                             */
                            switch (inFldIdx) {
                            case 1:
                                /*
                                 *      Rec 2, contains file header information (Total # of menus)
                                 */
                                if (inRecNum == 2) {
                                    inExpMenus = inFldVal;
                                    inNumMenus = 0;
                                    inExpItems = 1;     /* Expected items must not equal num items now */
                                    inNumItems = 0;
                                    fMenuHeader = VS_TRUE;
                                    /** /pdebug (("[%d] File Header (%d)",inRecNum, inExpMenus));*/
                                } else if (fMenuHeader) {
                                    /*
                                     *      Menu header contains the total # of items in this menu)
                                     */
                                    ++inNumMenus;
                                    inExpItems = inFldVal;
                                    inNumItems = 0;
                                    fMenuHeader = VS_FALSE;
                                    /** /pdebug (("[%d] Menu Header Exp %d, #%d, Exp %d)",
                                            inRecNum, inExpMenus, inNumMenus, inExpItems));*/
                                } else {
                                    /*
                                     *      Keep track of the menu items
                                     */
                                    ++inNumItems;
                                    /** /pdebug (("[%d] Item Exp %d, #%d",inRecNum, inExpItems, inNumItems));*/
                                }
                                srMenu.miItemKey = inFldVal;
                                break;
                            case 2:
                                srMenu.mlTranMsg = str2long(szTempBuffer);
                                /** /pdebug (("mlTranMsg=%ld",srMenu.mlTranMsg));*/
                                break;
                            case 3:
                                srMenu.mlTitleID = str2long(szTempBuffer);
                                /** /pdebug (("mlTitleID=%ld",srMenu.mlTitleID));*/
                                break;
                            case 4:
                                srMenu.mlPlaceHolder = str2long(szTempBuffer);
                                /** /pdebug (("mlTitleID=%ld",srMenu.mlPlaceHolder));*/
                                break;
                            case 5:
                                inFldVal = atoi(szTempBuffer);
                                srMenu.miPasswordLevel = inFldVal;
                                /** /pdebug (("miPasswordLevel=%d",srMenu.miPasswordLevel));*/
                                break;
                            case 6:
                                inFldVal = atoi(szTempBuffer);
                                srMenu.miPITIndex = inFldVal;
                                /** /pdebug (("miPITIndex=%d",srMenu.miPITIndex));*/
                                break;
                            case 7:
                                inFldVal = atoi(szTempBuffer);
                                srMenu.miReDisplayMenu = inFldVal;
                                /** /pdebug (("miReDisplayMenu=%d",srMenu.miReDisplayMenu));*/
                                break;
                            case 8:
                                inFldVal = atoi(szTempBuffer);
                                srMenu.miFuncIndex = inFldVal;
                                /** /pdebug (("miFuncIndex=%d",srMenu.miFuncIndex));*/
                                break;
                            case 9:
                                inFldVal = atoi(szTempBuffer);
                                srMenu.miSubFuncIndex = inFldVal;
                                /** /pdebug (("miSubFuncIndex=%d",srMenu.miSubFuncIndex));*/
                                /*
                                 *      Write menu struct to file
                                 */
                                if ((inResult = write(inHandle, (void *) &srMenu, sizeof(srMenu))) != sizeof(srMenu)) {
                                    extern int errno;
                                    /**/pdebug(("(%d) Write Failed=%d/%d", inRecNum, inResult, errno));/**/
                                    fReturnValue = VS_FALSE;
                                    break;
                                }
                                /** /pdebug (("rec=%d,IK=%d,TM=%ld,TID=%ld,PH=%ld,PW=%d,RD=%d,FI=%d,SF=%d.",
                                    inRecNum,
                                    srMenu.miItemKey,
                                    srMenu.mlTranMsg,
                                    srMenu.mlTitleID,
                                    srMenu.mlPlaceHolder,
                                    srMenu.miPasswordLevel,
                                    srMenu.miReDisplayMenu,
                                    srMenu.miFuncIndex,
                                    srMenu.miSubFuncIndex));*/
                                /*
                                 *      We have read the number of items we expected, next record
                                 *      should be a menu header.
                                 */
                                if (inNumItems == inExpItems) {
                                    /** /pdebug (("[%d] Next Menu %d=%d",inRecNum, inExpItems, inNumItems));*/
                                    fMenuHeader = VS_TRUE;
                                    inNumItems = 0;
                                }
                                break;
                            }
                            inFldIdx++;
                        }
                    }
                }
            }
            inRecNum++;
        }

        /*
         *      Close file if open
         */
        if (inHandle > 0) {
            if ((inResult = close(inHandle)) < 0) {
                extern int errno;
                /** /pdebug (("close failed %d/%d", inResult, errno));*/
                fReturnValue = VS_FALSE;
            }
        }

        if (fUpdateMenus) {
            /*
             *      Verify integrity of the menus file
             */
            if (fReturnValue && (inExpMenus != inNumMenus || inNumItems > 0)) {
                /** /
                pdebug (("%s Menu ERR (%d)\nMenus Exp. %d <--> %d\nItems Exp. %d <--> %d\nRecord = %d",
                    szTempFileName,
                    fReturnValue,
                    inExpMenus, inNumMenus,
                    inExpItems, inNumItems,
                    inRecNum));*/
                fReturnValue = VS_FALSE;
            }
        }
    }

    if (fUpdateMenus) {
        /**/
        pdebug(("Menu %s DONE\nMenus Exp. %d <--> %d\nItems Exp. %d <--> %d\nRecord = %d", szMenusFileName, inExpMenus, inNumMenus, inExpItems, inNumItems, inRecNum));/**/

        if (fReturnValue) {
            if (inRemoveFile(szMenusFileName) != VS_SUCCESS) {
                /**/pdebug(("%s remove failed!", szMenusFileName));/**/
                fReturnValue = VS_FALSE;
            }
        }

        if (fReturnValue) {
            if ((inResult = rename(TEMP_FILE_NAME, szMenusFileName)) != VS_SUCCESS) {
                extern int errno;
                fReturnValue = VS_FALSE;
            }
        }
    }

    return fReturnValue;
} /* End of fUpdateMenus () */

VS_BOOL fRootMenu(void) {
    VS_BOOL fReturnValue = VS_FALSE;

    if (pmeCurrentMenu->mMenuIdentifier == MENU_ROOT)
        fReturnValue = VS_TRUE;

    return fReturnValue;
}

int inDisplayMenu(int inMenuIndex,short shStyle) {
    int inEventCode;
    int inResult = VS_ERR;
    int inFunctionOffset;
    VS_BOOL fResetFont = VS_FALSE;

    /** /pdebug(("--inDisplayMenu--"));*/

    vdSelectDisplayMenu(inMenuIndex, shStyle);
    vdUpdateDisplayMenu(shStyle);

	inEventCode = inWaitKey(inGetIdleTimeOut());

    while (inEventCode) {
        if (inEventCode == KEY_CANCEL) {
            inResult = VS_ESCAPE;
            break;
        }
        if (inEventCode == KEY_BS) {
            vdFlushKeyboardBuffer();
            vdToggleArrow();
            continue;
        }

        /*
         * The current menu has a displayed menu list.
         * First, if there are enough menu items to require scrolling
         * through it, and the user presses the scroll key, then we scroll.
         */
        if ((inNumScrollingMenuItems >= shNumItemsPerDisplayPage(shStyle)) && ((inEventCode == inScrollLeftKey) || (inEventCode == inScrollRightKey))) {
            /*
             * Scroll through the list.
             */
            if (inEventCode == inScrollLeftKey) {
                inCurrentScrollItem -= shNumItemsPerDisplayPage(shStyle);

                // Attempting to scroll backward to first screen
                if (inCurrentScrollItem == -1)
                    inCurrentScrollItem = 0;
                // Attempting to scroll backward to last screen
                if (inCurrentScrollItem < 0)
                    inCurrentScrollItem = inNumScrollingMenuItems - (inNumberOfItemsAtEnd > 0 ? inNumberOfItemsAtEnd : ITEMS_PER_PAGE);
            } else {
                inCurrentScrollItem += shNumItemsPerDisplayPage(shStyle);

                // Attempting to scroll forward to first screen
                if (inCurrentScrollItem >= inNumScrollingMenuItems)
                    inCurrentScrollItem = 0;
            }
            if (shStyle == CHOICES_STYLE)
                vdDestroyOptWin3200();
            vdUpdateDisplayMenu(shStyle);
        } else if ((inFirstMenuKey <= inEventCode) && (inEventCode <= inLastMenuKey)) {
            /*
             * The user has chosen a menu item.
             */
            if (inDisplayLeftToRight)
                inFunctionOffset = inEventCode - inFirstMenuKey;
            else
                inFunctionOffset = inLastMenuKey - inEventCode;
            if ((inCurrentScrollItem + inFunctionOffset) < inNumScrollingMenuItems) {
                int inGetPwdResult;
                MenuItem* pmeChosenItem;

                if (shStyle == CHOICES_STYLE)
                    vdDestroyOptWin3200();
                clrscr();

                pmeChosenItem = &pmeScrollItem[inCurrentScrollItem + inFunctionOffset];
                if (pmeChosenItem->miFuncIndex > 0) {
                    if (obDisp.inCharsPerRow != 21) {
                        vdSetActionFont();
                        fResetFont = VS_TRUE;
                    }
                    inGetPwdResult = inGetPwdFromUser(pmeChosenItem->miPasswordLevel, pmeChosenItem->miPITIndex);
                    if (fResetFont)
                        vdSetMenuFont();
                    if (inGetPwdResult == VS_SUCCESS) {
                        inResult = pmeChosenItem->miFuncIndex;
                        break;
                    }
                } else {
                    if (obDisp.inCharsPerRow != 21) {
                        vdSetActionFont();
                        fResetFont = VS_TRUE;
                    }
                    inGetPwdResult = inGetPwdFromUser(pmeChosenItem->miPasswordLevel, pmeChosenItem->miPITIndex);
                    if (fResetFont)
                        vdSetMenuFont();
                    if (inGetPwdResult == VS_SUCCESS) {
                        vdSelectMenu(pmeChosenItem->miFuncIndex);
                        vdUpdateDisplayMenu(shStyle);
                    } else
                        vdBeep();
                }
            } else
                vdBeep();
        } else
            vdBeep();
    }

    /** /pdebug (("inResult = %d", inResult));*/
    if (shStyle == CHOICES_STYLE)
        vdDestroyOptWin3200();

    return (inResult);
}

void vdSelectDisplayMenu(int inMenuNum,short shStyle) {
    int inPrevIndex = 0,
    inPrevMenu = 0;
    long lnRes = 0L;
    static int inCntr = 0;

    /** /pdebug(("--vdSelectSubMenu(%d)--", inMenuNum));*/

    if (pmeCurrentMenu != NULL) {
        inPrevIndex = inCurrentMenuIndex;
        inPrevMenu = pmeCurrentMenu->mMenuIdentifier;
    }

    inCurrentMenuIndex = inGetIndexForMenu(inMenuNum);
    if (inCurrentMenuIndex > 0) {
        pmeCurrentMenu = &MenuList[inCurrentMenuIndex].meMenu;

        /*
         * Find the first menu item that's part of the scroll list.
         */
        pmeScrollItem = (MenuItem *) pmeCurrentMenu;
        inFirstScrollItem = inCurrentMenuIndex + 1;
        inNumScrollingMenuItems = pmeCurrentMenu->mNumMenuItems + 1;
        while (--inNumScrollingMenuItems && ((++pmeScrollItem)->miItemKey != ANY_KEY))
            ++inFirstScrollItem;

        /*
         *      Calculate # of items on last menu screen.
         */
        if (shStyle == MENUS_STYLE) {
            if (inNumScrollingMenuItems < ITEMS_PER_PAGE)
                inNumberOfItemsAtEnd = 0;
            else if (inNumScrollingMenuItems < 6)
                inNumberOfItemsAtEnd = (inNumScrollingMenuItems) % ITEMS_PER_FIRST_PAGE;
            else
                inNumberOfItemsAtEnd = (inNumScrollingMenuItems - ITEMS_PER_FIRST_PAGE) % ITEMS_PER_PAGE;
        } else {
            if (inNumScrollingMenuItems < ITEMS_PER_PAGE)
                inNumberOfItemsAtEnd = 0;
            else
                inNumberOfItemsAtEnd = (inNumScrollingMenuItems) % ITEMS_PER_PAGE;
        }

        pmeScrollItem = &MenuList[inFirstScrollItem].meItem;

        /*
         * Set the scroll list vars to -1 if no items are to be
         * in a scrolling list.
         */
        if (inNumScrollingMenuItems <= 0)
            inFirstScrollItem = -1;
        inCurrentScrollItem = 0;

        lnCurrentMenuTitle = pmeCurrentMenu->mMenuTitle;
    }
}

void vdUpdateDisplayMenu(short shStyle) {
    char szScrap[MESSAGE_SIZE + 1];
    //char szRJust[MESSAGE_SIZE + 1];
    char szItemText[4][MESSAGE_SIZE + 1];

    int inIndex;
    int inRemainingItems;
    MenuItem* pmeDisplayItem;

    int inCaratLine = 4;
    int inLineIncr = 1;
    int inLineLimit = 0;
    int inFirstLine = 1;
    static int inProcFs = 0;

    /*
     * turn-off datetime
     */
    inNoDisp = 1;

    switch (obDisp.inCharsPerRow) {
        // added__ML__03032000
    case 21:
        /*
           *  6x8 font
           */
        inCaratLine = 8;
        inLineLimit = obDisp.inCharsPerRow;
        inLineIncr = 2;
        break;

    case 16:
        /*
         *  8x16 font
           */
        inCaratLine = 4;
        inLineLimit = obDisp.inCharsPerRow;
        inLineIncr = 1;
        break;

    case 8:
        /*
           *  16x16 font
         */
        inCaratLine = 4;
        inLineLimit = obDisp.inCharsPerRow * 2;
        inLineIncr = 1;
        break;
    default:
        break;
    }

    if (inFirstScrollItem != ANY_KEY) {
        /*
         * Figure out how many menu items
         * remain to be displayed.
         */
        inRemainingItems = inNumScrollingMenuItems - inCurrentScrollItem;
        /*
         * We need both of the following tests for the following reason:
         *    1.  First, we make sure that the menu is spread out over
         *        several pages so we can leave space for the "More" arrow...
         *    2.    Second, we make sure that we have enough menu items
         *        left over...
         *    ...THEN we limit the number of items remaining to be displayed
         *        to the rest of the page.
         */

        obDisp.blCaratVis = VS_TRUE;

        if (inNumScrollingMenuItems <= shNumItemsPerDisplayPage(shStyle))
            obDisp.blCaratVis = VS_FALSE;

        pmeDisplayItem = &pmeScrollItem[inCurrentScrollItem - 1];

        if ((inNumScrollingMenuItems > shNumItemsPerDisplayPage(shStyle)) && (inRemainingItems >= shNumItemsPerDisplayPage(shStyle)))
            inRemainingItems = shNumItemsPerDisplayPage(shStyle);

        inProcFs = inFirstScreen(pmeDisplayItem + 1);
        inFirstMenuKey = KEY_e;
        inFirstLine = inFirstLn();
        if (inProcFs && shStyle == MENUS_STYLE) {
            /*
             *  On 3200, first root
             *  screen has 3 items.
             */
            inFirstMenuKey = KEY_f; /* disable key_e on first screen */

            inFirstLine = inFirstLn() + inLineIncr; /* time/date appear on line 1 */

            if (lnCurrentMenuTitle) {
                int inTitleColumn = 0;
                char szMenuTitle[MESSAGE_SIZE + 1];

                /*
                 * Change the title if menu has one.
                 */
                vdGetMessageFromFile(lnCurrentMenuTitle, szMenuTitle);
                if ((inTitleColumn = obDisp.inCharsPerRow / 2 - strlen(szMenuTitle) / 2) < 1)
                    inTitleColumn = 1;
                vdClearTitleLine();
                vdDisplayAt(inTitleColumn, obDisp.inTitleLine, szMenuTitle, CLR_EOL);
            }
        } else if (inProcFs && shStyle == CHOICES_STYLE) {
            if (pmeCurrentMenu->mLine2Msg)
                vdDispMsgAt(pmeCurrentMenu->mLine2Msg, 1, (inFirstLine + inLineIncr), CLR_EOL);
            if (pmeCurrentMenu->mLine3Msg)
                vdDispMsgAt(pmeCurrentMenu->mLine3Msg, 1, inFirstLine + (2 * inLineIncr), CLR_EOL);
        }

        /*
         * Get the menu text from the message file.
         */
        szItemText[0][0] = NULL_CH;
        szItemText[1][0] = NULL_CH;
        szItemText[2][0] = NULL_CH;
        szItemText[3][0] = NULL_CH;

        for (inIndex = 0; ((inIndex < 4) && (inIndex < inRemainingItems)); ++inIndex) {
            ++pmeDisplayItem;
            if ((pmeDisplayItem)->mlTitleID > 0L) {
                vdGetMessageFromFile(pmeDisplayItem->mlTitleID, szScrap);
                strncpy(szItemText[inIndex], szScrap, inLineLimit);
            }
        }

        if (shStyle == MENUS_STYLE) {
            /*
               * Now display the menu text, right justified;
             */
            if (!inProcFs)
                vdClearTitleLine();
            vdClearNonTitleLines();
            vdDispStrAtRight(szItemText[0], inFirstLine, NO_CLEAR);
            vdDispStrAtRight(szItemText[1], inFirstLine + inLineIncr, NO_CLEAR);
            vdDispStrAtRight(szItemText[2], inFirstLine + (2 * inLineIncr), NO_CLEAR);
            if (!inProcFs)
                vdDispStrAtRight(szItemText[3], inFirstLine + (3 * inLineIncr), NO_CLEAR);
        } else
            vdCreateOptWin3200(szItemText);

        if (obDisp.blCaratVis) {
            gotoxy(obDisp.inHomeCol, inCaratLine);
            if (obDisp.blCaratVis)
            {
		 // Rannie_B1 04262004: Fixed the bug wherein the down arrow icon is not shown
		 // if the language in use is not English
               //vdDisplayFontChar(UTILITY_FONT, obDisp.chCaratOffset);
               vdMLDisplayFontChar(UTILITY_FONT, obDisp.chCaratOffset, obDisp.inHomeCol, inCaratLine);
               // End Rannie_B1 04262004
	     }
            else
                vdWriteSpace();
        }
    }
} /* end vdUpdateMenu() */

short shNumItemsPerDisplayPage(short shStyle) {
    return (shStyle == MENUS_STYLE ? NUM_ITEMS_PER_PAGE : ITEMS_PER_PAGE);
}

int inC3IN_Functionality(TRANSACTION_OBJECT* pobTran) {
    int inRetVal = VS_SUCCESS;

    pdebug(("--inC3IN_Functionality--"));
    if (srGDS.fWirelessActive) {
#ifdef MOBITEX_DEFINED
        vdGetIdleRadioInput();
#endif
    } else
        inRetVal = inVeritalkDownload(pobTran);

    return (inRetVal);
}

int MENUFUNC_CODE_CHECK(char* a,char* b,short * c,char* d,unsigned char* e) {
    GET_VER(a, b, c, d, e);
    return 1;
}

void vdPrintDebugLog(void)
{
	int inConsoleHandle;
	int inLocalTaskID;
	int inConsoleOwnerTaskID;

	inLocalTaskID = get_task_id();
	inConsoleHandle = get_owner(DEV_CONSOLE, &inConsoleOwnerTaskID);
	LOG_PRINTFF((EESL_DEBUG_GLOBAL, "Local Task = %d : Console Handle = %d : Console Owner Task = %d", inLocalTaskID, inConsoleHandle, inConsoleOwnerTaskID));
}

int inICICICustomDeActivate()
{
	if(fRootMenu() != VS_TRUE)
	{
		LOG_PRINTFF((EESL_DEBUG_GLOBAL,"ICICI Not in Root Menu"));
		return(BRANCH_EXIT);
	}

	LOG_PRINTFF((EESL_DEBUG_GLOBAL,"ICICI Inside Root Menu"));
	return(inDoDeActivate());
}
#undef VSMENUS_C

//meca 20041023 -- fixed from cashcard O3750 -- for auto-processing in multi-app environment (bruce/sadiq) -- start
int inBackToIdle()
{
	int inRetVal = 0;

	if (inPostSelfActivate() == VS_SUCCESS)
	{
		LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Activate event received"));
		/* Open the Console */
		//LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Opening the console"));
		//hConsoleS = open(DEV_CONSOLE,0);
		//srGDS.fSoftPayActive = VS_TRUE;
		//inAppl_activate();
		inDoActivate();
#ifdef SERF_MENU
		refreshMenu();
#endif
		return VS_SUCCESS;
	}
	else
		return VS_ERR;
}


int inPostSelfActivate()
{
	return (inSendReceiveEvent(ACT_EVENT, ACT_EVENT));
}


int inSendReceiveEvent(short shInEvent, short shOutEvent)
{
	int inError = 0;
	event_t lnEvent;
	int inCustomEvt=0;
  //jrd one source
    #ifdef __arm
     unsigned short shEventDataSize =0;
    #endif
    #ifdef _TARG_68000
     unsigned int shEventDataSize =0;
    #endif
	

       char pchDummy[20];
       unsigned char puchData[255];
	
	LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Posting %d Event", shInEvent));
	inError = EESL_send_event("DEVMAN", shInEvent, NULL, 0);
	while(inError)
	{
		SVC_WAIT(200);
		inError = EESL_send_event("DEVMAN", shInEvent, NULL, 0);
	}//while - repeatedly send event
	

	/* Wait for a PIPE event, for DEVMAN to post back our output Event */
	while (EESL_queue_count() == 0) 				
	{
		LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Waiting for a PIPE event1"));
		while ((lnEvent = wait_event()) != EVT_PIPE)
		{
			SVC_WAIT(0);
		}
	}

	/* We have received a PIPE Event */
        LOG_PRINTFF((EESL_DEBUG_GLOBAL,"We have received a PIPE Event1"));

        {
            //char pchDummy[20];
            //unsigned char puchData[255];

            strcpy (pchDummy, "DUMMY");
            inCustomEvt = EESL_read_cust_evt(puchData,sizeof (puchData),&shEventDataSize,pchDummy);
            LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Event Received was %d ",inCustomEvt));

        }
        
	while (inCustomEvt != shOutEvent)
	{
        	 LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Event Received was %d ",inCustomEvt));
		/* If the devices are unavailable, then wait */
		if (inCustomEvt == APP_RES_SET_UNAVAILABLE)
		{
			SVC_WAIT(1600);
			LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Retry, Posting INIT Event"));
			inError = EESL_send_event("DEVMAN", shInEvent, NULL, 0);
			while(inError)
			{
				SVC_WAIT(200);
				inError = EESL_send_event("DEVMAN", shInEvent, NULL, 0);
			}
		
			/* Wait for a PIPE event, for DEVMAN to post back our Activate Event */
			while (EESL_queue_count() == 0) 				
			{
				LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Waiting for a PIPE event2"));
				while ((lnEvent = wait_event()) != EVT_PIPE)
				{
					SVC_WAIT(0);
				}
			}

			/* We have received a PIPE Event */
                    {
                        //char pchDummy[20];
                        //unsigned char puchData[255];
                        strcpy (pchDummy, "DUMMY");
                         inCustomEvt = EESL_read_cust_evt(puchData,sizeof (puchData),&shEventDataSize,pchDummy);
                    }
		}
		else
		{
		    LOG_PRINTFF((EESL_DEBUG_GLOBAL,"Received an Unknown Output event"));       
		    return VS_ERR;
		}
	}

	/* We finally got back our posted Event */
	return VS_SUCCESS;
}

//meca 20041023 -- fixed from cashcard O3750 -- for auto-processing in multi-app environment (bruce/sadiq) -- end

